工厂模式定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。
举个很简单的例子,中国生产了一批布,可以制作成衣服和裤子,并且在中国和美国都有工厂,可以这样定义类
定义一个抽象工厂类,用于定义方法,但具体的操作由各个分工厂自己操作
package com.hpg.demo.cloth;
public abstract class Factory {
public Cloth orderCloth(String JacketOrTrouse) {
Cloth cloth;
cloth = createCloth(JacketOrTrouse);
cloth.make();
cloth.labeling();
return cloth;
}
public abstract Cloth createCloth(String JacketOrTrouse);
}
定义一个Cloth类,Jacket和Trouse都继承这个类
package com.hpg.demo.cloth;
public abstract class Cloth {
/**
* 衣服还是裤子
*/
String typeName ;
/**
* 制作
*/
void make(){
System.out.println("simple make");
}
/**
* 贴标签
*/
void labeling(){
System.out.println("simple labeling");
}
}
定义AmericaFactory类
package com.hpg.demo.cloth;
public class AmericaFactory extends Factory {
@Override
public Cloth createCloth(String JacketOrTrouse) {
if (JacketOrTrouse.equals("jacket")) {
return new Jacket();
} else if (JacketOrTrouse.equals("trouse")) {
return new Trouse();
} else {
return null;
}
}
}
定义ChinaFactory类
package com.hpg.demo.cloth;
public class ChinaFactory extends Factory{
@Override
public Cloth createCloth(String JacketOrTrouse) {
if (JacketOrTrouse.equals("jacket")) {
return new Jacket();
} else if (JacketOrTrouse.equals("trouse")) {
return new Trouse();
} else {
return null;
}
}
}
定义Jacket类
package com.hpg.demo.cloth;
public class Jacket extends Cloth{
public Jacket(){
typeName = "jacket";
}
@Override
void make() {
System.out.println("make:"+typeName);
}
}
定义Trouse类
package com.hpg.demo.cloth;
public class Trouse extends Cloth{
public Trouse(){
typeName = "trouse";
}
@Override
void make() {
System.out.println("make:"+typeName);
}
}
测试类TestMain
package com.hpg.demo.cloth;
public class TestMain {
public static void main(String args[]){
Factory factory = new ChinaFactory();
factory.orderCloth("jacket");
}
}
执行结果:
make:jacket
simple labeling