参考:https://www.cnblogs.com/xuxinstyle/p/9128865.html
// 首先创建一个抽象类1
2
3
4
5
6public abstract class INoodles {
/**
* 描述每种面条啥样的
*/
public abstract void desc();
}
// 该抽象类的3个实现子类1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public class LzNoodles extends INoodles {
public void desc() {
System.out.println("兰州拉面");
}
}
public class PaoNoodles extends INoodles {
public void desc() {
System.out.println("泡面");
}
}
public class GankouNoodles extends INoodles {
public void desc() {
System.out.println("干扣面");
}
}
// 工厂类1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public class SimpleNoodlesFactory {
public static final int TYPE_LZ = 1; //兰州拉面
public static final int TYPE_PM = 2; //泡面
public static final int TYPE_GK = 3; //干扣面
//根据类型创建不同的对象实例
public static INoodles createNoodles(int type) {
switch (type) {
case TYPE_LZ:
return new LzNoodles();
case TYPE_PM:
return new PaoNoodles();
case TYPE_GK:
return new GankouNoodles();
default:
return new PaoNoodles(); //默认给一碗泡面
}
}
}