首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

设计形式之工厂模式2

2012-10-21 
设计模式之工厂模式2在前一篇介绍简单工厂模式中大家大家知道,要产生具体水果对象就必须去FriutFactory这

设计模式之工厂模式2
在前一篇介绍简单工厂模式中大家大家知道,要产生具体水果对象就必须去FriutFactory这个类中产生。这个类是一个水果的工厂。这个水果本身就是一个抽象概念。随着具体水果的增加和丰富,可能要更改FriutFactory这个类就比较频繁。因此工厂设计模式就在简单工厂设计模式上进行再次的抽象。这次抽象将按照具体的水果来进行抽象。比如苹果,那么就设计一个苹果工厂类,这个苹果工厂类就专门用来产生苹果对象。而联系到现实时候中工作分工的细化是一样的道理。
  下面直接看源码

//水果接口public interface Fruit {/* * 采集水果 */public void get();}//具体的水果苹果实现水果的接口public class Apple implements Fruit{public void get(){System.out.println("采集苹果");}}//具体的水果香蕉实现水果的接口public class Banana implements Fruit{public void get(){System.out.println("采集香蕉");}}//产生水果的工厂public interface FruitFactory {public Fruit getFruit();}//苹果类工厂,用于产生具体的苹果对象public class AppleFactory implements FruitFactory {public Fruit getFruit() {return new Apple();}}//香蕉类工厂,用于产生具体的香蕉对象public class BananaFactory implements FruitFactory {public Fruit getFruit() {return new Banana();}}

如果该果园最新又种植类李子。则以上代码不需要任何更改,只需加如下代码
// 李子public class Pear implements Fruit {public void get() {System.out.println("采集李子");}}//产生李子对象的工厂,增加不影响和不改动之前的代码public class PearFactory implements FruitFactory {public Fruit getFruit() {return new Pear();}}

Client端代码
public class Client{public static void main(String[] args) {//实例化AppleFactoryFruitFactory ff = new AppleFactory();Fruit apple = ff.getFruit();apple.get();FruitFactory ff2 = new BananaFactory();Fruit banana = ff2.getFruit();banana.get();FruitFactory ff3 = new PearFactory();Fruit pear = ff3.getFruit();pear.get();}}

以上代码就实现类工厂模式。你可以通过对比简单工厂模式和工厂模式来进行理解。工厂模式更具有扩展性。同时它对原有代码几乎是不变动的。

热点排行