Java设计模式之工厂方法模式

一、什么是工厂方法模式

  简单工厂模式属于类的创建型模式,又叫做多态工厂模式。工厂方法模式的意义是定义一个创建产品对象的工厂接口。将实际创建工作推迟到子类当中。核心工厂类不在负责创建产品。这样核心类就成为了一个抽象工厂角色。仅负责具体工厂子类必须实现的接口。这样进一步抽象化的好处是使得工厂方法模式可以使系统不修改具体工厂角色的情况下引进新的产品。

  Fruit类

public interface Fruit(){
 public void get();   

}

   Apple类

public class Apple implements Fruit{
 public void get(){
 System.out.println("我获取到了苹果..."); 
}   
}

 Banana类

public class Bananaimplements Fruit{
 public void get(){
 System.out.println("我获取到了香蕉..."); 
}   
}
FruitFactory 类  
public interface FruitFactory {
    public Fruit getFruit();
}

   AppleFactory工厂类

  

public class AppleFactory implements FruitFactory {

    public Fruit getFruit() {
        return new Apple();
    }

}

  BananaFactory工厂类

  


public class BananaFactory implements FruitFactory {

    public Fruit getFruit() {
        return new Banana();
    }

}

 此时如果要新增一个产品pear改如何做呢?

      我们只需要添加pear类和pear工厂

    Pear类

public class Pear implements Fruit {

	public void get() {
		System.out.println("采集梨子");
	}

}

    PearFactory工厂类

public class PearFactory implements FruitFactory {

    public Fruit getFruit() {
        return new Pear();
    }
}

    测试类Test

public class Test(){


    public static void main(String[] args) {
        //获得AppleFactory
        FruitFactory ff = new AppleFactory();
        //通过AppleFactory来获得Apple实例对象
        Fruit apple = ff.getFruit();
        apple.get();
        
        //获得BananaFactory
        FruitFactory ff2 = new BananaFactory();
        Fruit banana = ff2.getFruit();
        banana.get();
        
        //获得PearFactory
        FruitFactory ff3 = new PearFactory();
        Fruit pear = ff3.getFruit();
        pear.get();
    }

   二、模式中包含的角色和职能

   1.抽象工厂角色(creator)

    工厂方法模式的核心,任何工厂类都必须实现这个接口。

   2.具体工厂角色(concrete creator

   具体工厂类是抽象工厂的一个实现,负责实例化产品对象。

   3.抽象角色( product)

    工厂方法模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。

   4.具体产品角色(concrete product)

    工厂方法模式所创建的具体实例对象

  三、工厂方法模式与简单工厂模式的比较

     工厂方法模式与简单工厂模式在结构上的不同不是很明显。工厂方法类的核心是一个抽象工厂类,而简单工厂模式把核心放在一个具
体类上。
     工厂方法模式之所以有一个别名叫多态性工厂模式是因为具体工厂类都有共同的接口,或者有共同的抽象父类。

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

原文地址:https://www.cnblogs.com/LT0314/p/3892537.html