设计模式之工厂方法
来源:互联网 发布:缺乏安全感怎么办知乎 编辑:程序博客网 时间:2024/06/07 22:22
四种角色:抽象工厂,具体工厂,抽象产品,具体产品,具体工厂和具体产品之间是一对一的关系
抽象工厂一般由抽象类或者接口实现:
public interface Factory { Car create();}
具体工厂是具体的类,实现了抽象工厂中的方法,两个具体工厂如下所示:
public class BenzFactory implements Factory { public Car create() { return new BenzCar(); }}
public class BmwFactory implements Factory { public Car create() { return new BmwCar(); }}
抽象产品一般由抽象类或者接口实现:
public interface Car { void run();}
具体产品是具体的类,实现了抽象产品中的方法,两个具体产品如下所示:
public class BenzCar implements Car { public void run() { System.out.println("Benz run"); }}
public class BmwCar implements Car{ public void run() { System.out.println("Bmw run"); }}
测试类如下所示:
public class Customer { public static void main(String[] args) { Factory factory = new BenzFactory(); Car car = factory.create(); car.run(); factory = new BmwFactory(); car = factory.create(); car.run(); }}
输出结果:
Benz run
Bmw run
0 0
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式 之 工厂方法
- 设计模式 之 工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 设计模式之工厂方法
- 《设计模式》之工厂方法
- 设计模式之--工厂方法
- Python的灵活性--初级函数
- OpenStack部署前准备
- 关于Kafka
- [LeetCode]Buy and Sell Stocks 买卖股票问题
- 老司机带你玩转web service
- 设计模式之工厂方法
- 【NOIP2016提高A组模拟9.9】运输妹子
- Java学习之Iterator(迭代器)的一般用法 (转)
- 第一行代码酷欧天气开发详细总结
- IIS7/8 出现HTTP 500内部服务器错误解决方案
- 成员函数的识别
- 关于卸载linux的方法
- Webpack 入门指迷
- 当移动端软键盘弹出时错位问题解决方案