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

王朝java/jsp·作者佚名  2008-05-31
宽屏版  字体: |||超大  

一 、工厂方法(Factory Method)模式

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

二、 工厂方法模式角色与结构

抽象工厂(Creator)角色:是工厂方法模式的核心,与应用程序无关。任何在模式中创建的对象的工厂类必须实现这个接口。

具体工厂(Concrete Creator)角色:这是实现抽象工厂接口的具体工厂类,包含与应用程序密切相关的逻辑,并且受到应用程序调用以创建产品对象。在上图中有两个这样的角色:BulbCreator与TubeCreator。

抽象产品(PRodUCt)角色:工厂方法模式所创建的对象的超类型,也就是产品对象的共同父类或共同拥有的接口。在上图中,这个角色是Light。

具体产品(Concrete Product)角色:这个角色实现了抽象产品角色所定义的接口。某具体产品有专门的具体工厂创建,它们之间往往一一对应。

三、一个简单的实例

// 产品 Plant接口

public interface Plant { }

//具体产品PlantA,PlantB

public class PlantA implements Plant {

public PlantA () {

System.out.println("create PlantA !");

}

public void doSomething() {

System.out.println(" PlantA do something ...");

}

}

public class PlantB implements Plant {

public PlantB () {

System.out.println("create PlantB !");

}

public void doSomething() {

System.out.println(" PlantB do something ...");

}

}

// 产品 Fruit接口

public interface Fruit { }

//具体产品FruitA,FruitB

public class FruitA implements Fruit {

public FruitA() {

System.out.println("create FruitA !");

}

public void doSomething() {

System.out.println(" FruitA do something ...");

}

}

public class FruitB implements Fruit {

public FruitB() {

System.out.println("create FruitB !");

}

public void doSomething() {

System.out.println(" FruitB do something ...");

}

}

// 抽象工厂方法

public interface AbstractFactory {

public Plant createPlant();

public Fruit createFruit() ;

}

//具体工厂方法

public class FactoryA implements AbstractFactory {

public Plant createPlant() {

return new PlantA();

}

public Fruit createFruit() {

return new FruitA();

}

}

public class FactoryB implements AbstractFactory {

public Plant createPlant() {

return new PlantB();

}

public Fruit createFruit() {

return new FruitB();

}

}

四、工厂方法模式与简单工厂模式

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

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

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

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有