简单工厂模式
源码:
抽象产品
package com.kinglun.designPattern._1factory.simple;
//产品接口 其他产品必须实现这个接口
public interface Mobile {
public String mobileInfo();
}
具体产品
package com.kinglun.designPattern._1factory.simple;
//手机苹果信息
public class Apple implements Mobile {
@Override
public String mobileInfo() {
return "产品名:苹果,价格:¥5888,cpu:2,产地:美国";
}
}
package com.kinglun.designPattern._1factory.simple;
//三星实现手机的接口
public class Samsung implements Mobile {
@Override
public String mobileInfo() {
return "产品名:三星,价格:¥3444,cpu:2,产地:韩国";
}
}
package com.kinglun.designPattern._1factory.simple;
//手机工厂
public class MobilFactory {
//静态方法创建手机
public static Mobile creatMobile(String mobilName){
Mobile mobile = null;
switch (mobilName) {
case "Samsung":
mobile = new Samsung();
break;
case "Apple":
mobile = new Apple();
break;
}
return mobile;
}
}
测试
package com.kinglun.designPattern._1factory.simple;
public class Test {
public static void main(String[] args) {
Mobile samsung = MobilFactory.creatMobile("Samsung");
System.out.println(samsung.mobileInfo());
Mobile apple = MobilFactory.creatMobile("Apple");
System.out.println(apple.mobileInfo());
}
}
上一篇: 减脂咖啡的原理以及注意事项
下一篇: 设计模式之从简单工厂到泛型简单工厂