您的位置:首页 > 其它

工厂模式之工厂方法模式

2015-08-12 14:29 120 查看
先看代码:

publicinterface Product
{
publicvoid getName();
}

publicclass AProduct implements Product{
publicvoid getName()
{
System.out.println("I
am product A");
}
}

publicclass BProduct implements Product{
publicvoid getName()
{
System.out.println("I
am product B");
}
}

publicinterface IFactory
{
Product createProduct();
}

publicclass AFactory implements IFactory{
public Product
createProduct() {
returnnew AProduct();
}
}

publicclass BFactory implements IFactory{
public Product
createProduct() {
returnnew BProduct();
}
}

publicclass Test
{
publicstaticvoid main(String
[]args){
IFactory
iFactory = new AFactory();
Product product = iFactory.createProduct();
product.getName();
iFactory
= new BFactory();
product = iFactory.createProduct();
product.getName();
}
}

如果后来增加一类产品C,只需要增加一个C的工厂(CFactory类)和一个C产品的实现类(CProduct类),不过要修改客户端的代码,根据实际情况使用new AFactory()还是new BFactory()等等。
工厂方法模式优点:
每个工厂类对应一个对象的实现类,但需要客户端判断创建哪个工厂类实例,需求变化时,工厂类无需改变,但客户端需要修改。
简单工厂模式优点:
工厂类中包含必要的逻辑判断,客户端只需传递相应的参数便可得到想要的对象的实例化,在需求变化时,只需要修改工厂类,增加额外判断,客户端基本不用修改。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: