您的位置:首页 > 其它

工厂方法设计模式

2014-05-23 16:36 183 查看
工厂方法设计模式:定义一个用于创建对象的接口,让子类来决定来创建具体的对象。在类的结构上,对象子类与工厂子类是平行关系的。

下面我们看一个简单的例子:

package net.itaem.create;

/**
 * 接口:代表工厂要生产的对象
 * */
public interface Fruit {
    public void name();
    public void price();
}


package net.itaem.create;

/**
 * 具体的产品
 * */
public class Apple implements Fruit{

	@Override
	public void name() {
		System.out.println("the product name is apple");
	}

	@Override
	public void price() {
		System.out.println("the apple price is 10");
	}

}


package net.itaem.create;

/**
 * 具体的产品
 * */
public class Banana implements Fruit {

	@Override
	public void name() {
		System.out.println("the product is Banana");
	}

	@Override
	public void price() {
		System.out.println("the banana price is 10");
	}

}


package net.itaem.create;

/**
 * 定义一个工厂类,每个Concrete Factory负责生产具体的对象
 * */
public abstract class FruitFactory {
    public abstract Fruit create();
}


package net.itaem.create;

public class AppleFactory extends FruitFactory{

	@Override
	public Fruit create() {
		return new Apple();
	}

}


package net.itaem.create;

public class BananaFactory extends FruitFactory{

	@Override
	public Fruit create() {
		return new Banana();
	}

}


package net.itaem.create;

public class FactoryManager {
	private FruitFactory factory;

	/**
	 * 通过配置文件,读取具体的Factory对象
	 * */
	public FactoryManager(FruitFactory factory){
		this.factory = factory;
	}
    
	public void setFruitFactory(FruitFactory factory){
		this.factory = factory;
	}
	
	public Fruit create(){
		return factory.create();
	}
	
	public static void main(String[] args) {
		System.out.println("-----------------------apple ---------------- ");
		FactoryManager fruitFactory = new FactoryManager(new AppleFactory());
		Fruit fruit = fruitFactory.create();
		fruit.name();
		fruit.price();
		
		System.out.println("-----------------change to banana-------------------");
		<span style="color:#ff0000;">fruitFactory.setFruitFactory(new BananaFactory());
		fruit = fruitFactory.create();
		fruit.name();
		fruit.price();	
	}
}


下面是程序的输出结果

-----------------------apple ---------------- 
the product name is apple
the apple price is 10
-----------------change to banana-------------------
the product is Banana
the banana price is 10


类图结构:



从上面的例子,我们可以发现,每个类对应着一个工厂类(Apple->AppleFactory,Banana->BananaFactory)。如果我的程序需要添加新的产品对象,比如是西瓜,桃子等其它水果,那么我也要添加相应的工厂类。通过这种方式,程序将变得很灵活。在程序中,我们可以将具体的的工厂类设置在一个xml文件中,每次如果需要修改,直接修改xml配置文件即可,而不需要修改源代码,实现了开闭原则(对扩展开放,对修改关闭)。

总结:工厂方法是一种灵活的设计方式,该设计模式相对于静态工厂设计模式的最大优点就是,可以方便的扩展新的子类。

缺点:如果类过多,工厂对象的继承结构将会出现庞大的类。比如有1000种水果,那么就会有1000个工厂。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: