论坛首页 入门技术论坛

Java工厂模式

浏览 4615 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-06-20   最后修改:2009-09-14
1. 简单工厂模式
   
    publci class Sample{
       ....
    }
   
    public class A extends Sample{
       ....
    }

    public class B extends Sample{
       ......
    }
    

    工厂类处于决定实例化那个产品类的中心位置
   
    public class Factory{

       //静态工厂方法,无必要再去实例化这个工厂类,增加没有必要的代码
       public static Sample create(int which){
         if(which==1)
            return new A();
         if(which==2)
            return new B();
       }
    }
    

    使用简单工厂初始化一个类
    Sample newSample=Factory.create(1);


2. 工厂方法模式
    植物接口及两个实现类
   
    public interface Plant{}
 
    public class PlantA implements Plant{
    }
 
    public class PlantB implements Plant{
    }
    


    水果接口及两个实现类
    
    public interface Fruit{}

    public class FruitA implements Fruit{
    }
    
    public class FruitB implements Fruit{
    }
    


    抽象工厂
    
    public interface AbstractFactory{
         public Plant createPlant();
         public Fruit creatFruit();
    }
    


    工厂类A
   
    public Class FactoryA implements AbstractFactory{
         public Plant createPlant(){
            return new PlantA();
         }
         public Fruit creatFruit(){
            return new FruitA();
         }
    }
    

    工厂类B
   
    public Class FactoryB implements AbstractFactory{
         public Plant createPlant(){
            return new PlantB();
         }
         public Fruit creatFruit(){
            return new FruitB();
         }
    }
    

     工厂方法模式与简单工厂模式再结构上的不同不是很明显。工厂方法类的核心是一个抽象工厂类,而简单工厂模式把核心放在一个具体类上。

  工厂方法模式之所以有一个别名叫多态性工厂模式是因为具体工厂类都有共同的接口,或者有共同的抽象父类。

  当系统扩展需要添加新的产品对象时,仅仅需要添加一个具体对象以及一个具体工厂对象,原有工厂对象不需要进行任何修改,也不需要修改客户端,很好的符合了"开放-封闭"原则。而简单工厂模式在添加新产品对象后不得不修改工厂方法,扩展性不好。

  工厂方法模式退化后可以演变成简单工厂模式。

    新增加一个类PlantC 和 FruitC
  
   public class PlantC implements Plant{
    }
   public class FruitC implements Fruit{
    }
   

   这时只需要增加一个工厂类C
  
    public Class FactoryC implements AbstractFactory{
         public Plant createPlant(){
            return new PlantC();
         }
         public Fruit creatFruit(){
            return new FruitC();
         }
    }
    




   
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics