首页 > 学院 > 开发设计 > 正文

java设计模式之工厂方法模式

2019-11-14 09:33:03
字体:
来源:转载
供稿:网友

工厂方法模式:定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。

烤鱼店之工厂模式类图: 烤鱼店之工厂模式类图 FactoryFish中的Fish实例化延迟到子类NianYuFactory,JiYuFactory中来实例化。这是工厂方法模式和简单工厂模式的区别。

Fish类代码实现:

public class Fish { String name = "Unknow name";}

NianYu类代码实现:

public class NianYu extends Fish{ public NianYu() { // TODO Auto-generated constructor stub name = "鲶鱼"; System.out.PRintln("一条烤"+name); }}

JiYu类代码实现:

public class JiYu extends Fish{ public JiYu() { // TODO Auto-generated constructor stub name = "鲫鱼"; System.out.println("一条烤"+name); }}

FactoryFish类代码实现:

public abstract class FactoryFish { public abstract Fish createFish(); }

NianYuFactory类代码实现:

public class NianYuFactory extends FactoryFish{ @Override public Fish createFish() { // TODO Auto-generated method stub return new NianYu(); }}

JiYuFactory类代码实现:

public class JiYuFactory extends FactoryFish{ @Override public Fish createFish() { // TODO Auto-generated method stub return new JiYu(); }}

KaoYu类代码实现:

public class KaoYu { FactoryFish factoryFish; public KaoYu(FactoryFish factoryFish){ this.factoryFish =factoryFish; } public void orderFish(){ factoryFish.createFish(); }}

FishTest类代码实现:

public class FishTest { public static void main(String[] args){ FactoryFish factoryFish = new JiYuFactory(); KaoYu kaoYu = new KaoYu(factoryFish); kaoYu.orderFish(); FactoryFish factoryFish2 = new NianYuFactory(); KaoYu kaoYu2 = new KaoYu(factoryFish2); kaoYu2.orderFish(); }}

运行结果:

一条烤鲫鱼一条烤鲶鱼
上一篇:1042. 字符统计(20)

下一篇:0013 接口

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表