简单工厂(Simple Factory)

简单工厂并不算23种基本设计模式,应该算是一种编程习惯:

简单工厂(Simple Factory)_第1张图片

public class PizzaStore {
	public Pizza orderPizza(String type){
		Pizza pizza;
		if(null != type && type == "Greek"){
			pizza = new GreekPizza();
		}else if(null != type && type == "Cheese"){
			pizza = new CheesePizza();
		}else{
			pizza = null;
		}
		return pizza;
	}
}

具体Pizza类如GreekPizza以及CheesePizza和PizzaStore相耦合,导致具体Pizza的变动(添加一种新Pizza)必然会导致PizzaStore类的变动

	if(null != type && type == "Greek"){
			pizza = new GreekPizza();
		}else if(null != type && type == "Cheese"){
			pizza = new CheesePizza();
		}else{
			pizza = null;
		}

如果将具体Pizza类的生成过程独立出去,单独封装,具体Pizza类将与PizzaStore类解耦:

简单工厂(Simple Factory)_第2张图片

public class PizzaStore {
	public Pizza orderPizza(String type){
		PizzaFactory pf = new PizzaFactory();
		Pizza pizza = pf.createPizza(type);
		return pizza;
	}
}
public class PizzaFactory {
	public Pizza createPizza(String type){
		Pizza pizza;
		if(null != type && type == "Greek"){
			pizza = new GreekPizza();
		}else if(null != type && type == "Cheese"){
			pizza = new CheesePizza();
		}else{
			pizza = null;
		}
		return pizza;
	}
}

具体Pizza类的变动将不再会对PizzaStore类产生影响,从某种意义上说,简单工厂将具体Pizza类的变化封装在工厂内部,对外提供始终如一的服务

Pizza类的生成流程不再是在PizzaStore类内部实现,而是抽象为一个工厂方法,提高了Pizza类生成流程的复用性


ps:

工厂方法的作用是实现类的提供者(PizzaStore)与具体类(CheesePizza、GreekPizza)之间的解耦


你可能感兴趣的:(简单工厂(Simple Factory))