cstriker1407的笔记本

好记性不如铅笔头

java, 编程, 设计模式

设计模式学习笔记:桥梁模式

最近在看《设计模式之禅》这本书,收获良多,作者不愧是工作多年的大牛,将各种设计模式讲解的非常透彻。这里备份下书中的【 桥梁模式 】代码:

github:

https://github.com/cstriker1407/design_pattern 】

abstraction包:

Factory:

public abstract class Factory
{
	private Product product;
	
	public Factory(Product product)
	{
		super();
		this.product = product;
	}

	public void makeMoney()
	{
		product.beProducted();
		product.beSelled();
	}
}
public class HouseFactory extends Factory
{
	public HouseFactory(House house)
	{
		super(house);
	}

	@Override
	public void makeMoney()
	{
		super.makeMoney();
		System.out.println("house factory make money");
	}
}
public class SanzaiFactory extends Factory
{
	public SanzaiFactory(Product product)
	{
		super(product);
	}

	@Override
	public void makeMoney()
	{
		super.makeMoney();
		System.out.println("sanzai factory make money");
	}
}

 implementor:

public abstract class Product
{
	public abstract void beProducted();
	public abstract void beSelled();
}
public class House extends Product
{
	@Override
	public void beProducted()
	{
		System.out.println("House is producted");
	}

	@Override
	public void beSelled()
	{
		System.out.println("House is selled");
	}
}
public class IPod extends Product
{
	@Override
	public void beProducted()
	{
		System.out.println("IPod is producted");
	}

	@Override
	public void beSelled()
	{
		System.out.println("IPod is selled");
	}
}
public class Mp3 extends Product
{
	@Override
	public void beProducted()
	{
		System.out.println("Mp3 is producted");
	}

	@Override
	public void beSelled()
	{
		System.out.println("Mp3 is selled");
	}
}

 测试代码:

public class BridgeTest
{
	public static void test()
	{
		House house = new House();
		HouseFactory houseFactory = new HouseFactory(house);
		houseFactory.makeMoney();
		
		Mp3 mp3 = new Mp3();
		SanzaiFactory sanzaiFactory = new SanzaiFactory(mp3);
		sanzaiFactory.makeMoney();
	}
}

 备注:

通过代码可以发现,由于Factory中引用了Product,通过这层桥梁关系,当Product更改时,Factory可以快速的更改业务。

Leave a Reply

17 − 8 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Theme by Anders Norén

苏ICP备16032087号