工厂模式
该模式通过向工厂传递类型来指定要创建的对象。
XiaoMiPhone ,小米手机
public interface XiaoMiPhone {
void buy();
}
XiaoMi7
class XiaoMi7 implements XiaoMiPhone{
public void buy() {
System.out.println("购买了XiaoMi7");
}
}
XiaoMi8
class XiaoMi8 implements XiaoMiPhone{
public void buy() {
System.out.println("购买了XiaoMi8");
}
}
XiaoMi9
class XiaoMi9 implements XiaoMiPhone{
public void buy() {
System.out.println("购买了XiaoMi9");
}
}
XiaoMiFactory ,小米旗舰店,告知你要买的手机型号就可以得到对应的对象。
public class XiaoMiFactory {
public static XiaoMiPhone getXiaoMiPhone(String type){
if("小米7".equals(type)){
return new XiaoMi7();
}else if("小米8".equals(type)){
return new XiaoMi8();
}else if("小米9".equals(type)){
return new XiaoMi9();
}else{
throw new RuntimeException("小米暂时没有这种型号的手机哦!");
}
}
}
TestFactor ,测试类
public class TestFactor {
public static void main(String[] args) {
XiaoMiPhone mi7 = XiaoMiFactory.getXiaoMiPhone("小米7");
mi7.buy();
XiaoMiPhone mi8 = XiaoMiFactory.getXiaoMiPhone("小米8");
mi8.buy();
XiaoMiPhone mi9 = XiaoMiFactory.getXiaoMiPhone("小米9");
mi9.buy();
XiaoMiPhone mi10 = XiaoMiFactory.getXiaoMiPhone("小米10");
}
}