《23天设计模式之工厂模式》这是我的第三篇博客,继续昨天的单例模式,今天我们来了解一下工厂模式。顺便提一句,学习设计模式可能会有一种笼统的感觉,我们可以多去画一下模型图来加深映像。
直接上代码:
//产品接口
public interface Phone {
void call();
}
//苹果
public class Apple implements Phone{
@Override
public void call() {
System.out.println("苹果手机打电话");
}
}
public class HuaWei implements Phone{
@Override
public void call() {
System.out.println("华为手机打电话");
}
}
//华为
public class SimpleFactory {
//静态工厂--我们新增产品,肯定要修改这一块的代码
public static Phone getPhone(String phoneName){
if ("华为".equals(phoneName)) {
return new HuaWei();
} else if ("苹果".equals(phoneName)) {
return new Apple();
} else {
System.out.println("没有该品牌手机");
return null;
}
}
}
//客户端
public class Client {
public static void main(String[] args) {
Phone phone = SimpleFactory.getPhone("苹果");
phone.call();
}
}
//产品接口
public interface Phone {
void call();
}
//产品
public class Apple implements Phone {
@Override
public void call() {
System.out.println("苹果手机打电话");
}
}
public class HuaWei implements Phone {
@Override
public void call() {
System.out.println("华为手机打电话");
}
}
public class XiaoMi implements Phone{
@Override
public void call() {
System.out.println("小米手机打电话");
}
}
//工厂接口
public interface PhoneFactory {
Phone getPhone();
}
//工厂
public class AppleFactory implements PhoneFactory {
@Override
public Phone getPhone() {
return new Apple();
}
}
public class HuaWeiFactory implements PhoneFactory {
@Override
public Phone getPhone() {
return new HuaWei();
}
}
public class XiaoMiFactory implements PhoneFactory {
@Override
public Phone getPhone() {
return new XiaoMi();
}
}
//客户端
public class Client {
public static void main(String[] args) {
//这些工厂就是一家家专卖店
AppleFactory appleFactory = new AppleFactory();
HuaWeiFactory huaWeiFactory = new HuaWeiFactory();
XiaoMiFactory xiaoMiFactory = new XiaoMiFactory();
//用户决定去哪家专卖店就调用谁的方法
Phone phone = xiaoMiFactory.getPhone();
phone.call();
}
}
感谢您花时间阅读我的博客,以上就是我对工厂模式的一些理解,若有不对之处,还望指正,期待与您交流。
本篇博文系原创,仅用于个人学习,转载请注明出处。
原文:https://www.cnblogs.com/guying-blog/p/14659851.html