工场设计模式的优点:
面向接口编程,体现了面向对象的思想。
将创建对象的工作转移到了工场类。
**1.先创建一个抽象的父类
**public abstract class Coffer {
public abstract String getName();
}**
2.子类:美式咖啡
public class Americano extends Coffer {
@Override
public String getName() {
// TODO Auto-generated method stub
return “美式咖啡”;
}
public int math(int x) {
if (x != 0) {
x += x;
} else {
x += x + 1;
}
return x;
}
}**
3.子类:卡布奇诺
public class Cappuccino extends Coffer {
@Override
public String getName() {
// TODO Auto-generated method stub
return "卡布奇诺";
}
}
4.子类:拿铁
public class Latte extends Coffer {
@Override
public String getName() {
// TODO Auto-generated method stub
return "拿铁";
}
}
5.工场类
public class SimpleFactory {
public static Coffer createInstance(String type) {
if (“americano”.equals(type)) {
return new Americano();
}else if (“cappuccino”.equals(type)) {
return new Cappuccino();
}else if (“latte”.equals(type)) {
return new Latte();
}else {
throw new RuntimeException(“type[”+type+"]类型不可识别,没有匹配到可实例化的对象!");
}
}
}
6.客户端调用
public static void main(String[] args) {
Coffer americano = SimpleFactory.createInstance(“americano”);
String string = americano.getName();
int a = ((Americano) americano).math(5);
System.out.println(string);
System.out.println(a);
}