建立产品
public class Pizz {
public Pizz() {
System.out.println("##########Pizz ############");
}
}
子类
package com.ghg.data_structure.mode.factory;
public class CheesePizz extends Pizz {
public CheesePizz() {
System.out.println("CheesePizz 初始化");
}
}
package com.ghg.data_structure.mode.factory;
public class VeggiePizz extends Pizz {
public VeggiePizz() {
System.out.println("VeggiePizz 初始化");
}
}
工厂
package com.ghg.data_structure.mode.factory;
/**
* 简单工厂
*
* @author Administrator
*
*/
public class SimplePizzFactory {
public static Pizz createPrizz(String type) {
Pizz prizz = null;
if (type.equals("cheese")) {
prizz = new CheesePizz();
} else if (type.equals("veggie")) {
prizz = new VeggiePizz();
}
return prizz;
}
}
测试
public class Test1 {
public static void main(String[] args) {
Pizz cheese = SimplePizzFactory.createPrizz("cheese");
Pizz veggie = SimplePizzFactory.createPrizz("veggie");
}
}
结果
##########Pizz ############
CheesePizz 初始化
##########Pizz ############
VeggiePizz 初始化
package com.ghg.data_structure.mode.factory;
public class PizzStore {
private SimplePizzFactory simplePizzFactory;
/**
* 装饰模式 注入构造方法
* @param simplePizzFactory
*/
public PizzStore(SimplePizzFactory simplePizzFactory) {
this.simplePizzFactory = simplePizzFactory;
}
/**
* 生产PIZZ
* @param type
* @return
*/
@SuppressWarnings("static-access")
public Pizz orderPizz(String type){
Pizz pizz=null;
pizz=simplePizzFactory.createPrizz(type);
return pizz;
}
}
测试
package com.ghg.data_structure.mode.factory;
public class Test1 {
public static void main(String[] args) {
Pizz cheese = SimplePizzFactory.createPrizz("cheese");
Pizz veggie = SimplePizzFactory.createPrizz("veggie");
PizzStore pizzStore = new PizzStore(new SimplePizzFactory());
Pizz cheese2=pizzStore.orderPizz("cheese");
Pizz veggie2=pizzStore.orderPizz("veggie");
}
}
结果:
##########Pizz ############
CheesePizz 初始化
##########Pizz ############
VeggiePizz 初始化
##########Pizz ############
CheesePizz 初始化
##########Pizz ############
VeggiePizz 初始化
网友评论