创建型模式--工厂方法模式(Factory Method)

 Factory Method:Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

工厂方法模式又叫虚拟构造子(Virtual Constructor)模式。

一:引入

      Simple Factory在一定程度上支持OCP,但并没有完全支持OCP,其一缺点为当有新的产品加入到系统中时还必须修改工厂类。

public   interface  FruitFactory  {
    
public Fruit createFruit();
}


public   class  AppleFactory  implements  FruitFactory  {
    
public Fruit createFruit()
    
{
        
return new Apple();
    }

}



public   class  Client {

       
public static  Fruit getEatFruit()
       
{
           Fruit fruit
=null;
           FruitFactory fruitFactory
=new AppleFactory();
           fruit
=fruitFactory.createFruit();
           fruit.pick();
           fruit.peel();
           
           
return fruit;
           
       }

       
       
public static void main(String args[])
       
{
           getEatFruit();
       }

      
}

// 这样有新的产品加入时,只要加入对应的Factory,不用修改Simple Factory 中创建部分的代码

 

二:结构

三:实际应用

  1. EJB技术构架中
Context ctx = new  InitContext();
EmployeeHome home
= (EmployeeHome )ctx.lookup( " Employee " ); // 得到Concrete Factory (EmployeeHome)
Employee emp = home.create( 1001 , " andy " , " Smith " ); // 创建Concrete Product(Employee)
emp.setTel( " 010-1234343 " );

 

四:适用情形

Use the Factory Method pattern when

  • a class can't anticipate the class of objects it must create.
  • a class wants its subclasses to specify the objects it creates.
  • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

接口稳定,创建的具体类不可预料,经常变;

当然如果这个类十分稳定,就没有必要用Factory模式,如String类,十分稳定,没有其它的子类。

参考文献:
1:阎宏,《Java与模式》,电子工业出版社
2:Eric Freeman & Elisabeth Freeman,《Head First Design Pattern》,O'REILLY
3:GOF ,《designpatterns-elements.of.reuseable.object-oriented.software》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值