A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© binghaiwang 中级黑马   /  2013-8-24 15:24  /  916 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 binghaiwang 于 2013-8-25 11:34 编辑
  1. <p>package com.itheima.design;

  2. public class FactoryDesign {
  3. public static void main(String[] args) {
  4.                
  5.                 IFactory factory = new Factory();
  6.                 IProduct product = factory.creadteProduct();
  7.                 product.productMethod();
  8.         }

  9. }

  10. interface IProduct{
  11.         public void productMethod();
  12. }

  13. interface IFactory{
  14.         public IProduct creadteProduct();
  15. }

  16. class Product implements IProduct{

  17.         @Override
  18.         public void productMethod() {
  19.                 System.out.println("产品");
  20.         }

  21. }
  22. class Factory implements IFactory{

  23.         @Override
  24.         public IProduct creadteProduct() {
  25.                
  26.                 return new Product();
  27.         }
  28.         
  29. }</p>
复制代码
上述是否属于抽象化工厂设计模式,如果不是,请简要说明下抽象化工厂设计模式的要点。最好附个简单代码例子(带注释)

评分

参与人数 1技术分 +1 收起 理由
张智文 + 1

查看全部评分

1 个回复

倒序浏览
自己通过一些资料学习,我上述代码是工厂方法模式,而抽象工厂模式与工厂方法模式的主要区别在于体现在产品等级结构的不同,前者产品结构多级化,而后者产品等级结构比较单一,例如生产汽车行业,汽车会有2厢和3厢的区别,还有排量的区别,比如说有2.0和3.0的区别。那么这个2厢和3厢的车就是体现了产品等级结构的不同,而排量的不同称之为产品族的不同。在具体一点就是说,2.0、2厢的车子跟3.0、2厢的车子属于同一个等级结构,而2.0 、3厢的车子跟3.0、3厢的车子属于另一个等级结构,而同种排量不同厢数属于同一个产品族,反之则不同。总而言之,就是对产品从整体上先做一个产品等级结构划分,进而内部的一些属性再进行细分为产品族。
那么如果上述的工厂方法模式变为了抽象工厂模式后的代码如下:
  1. package com.itheima.design;

  2. public class FactoryDesign2 {

  3.         /**
  4.          * 抽象工厂模式
  5.          */
  6.         public static void main(String[] args) {
  7.                 Factory1 factory = new Factory1();
  8.                 factory.creadteProduct1().show();
  9.                 factory.creadteProduct2().show();
  10.         }
  11. }

  12. // 产品接口
  13. interface IProduct1 {
  14.         public void show();
  15. }

  16. interface IProduct2 {
  17.         public void show();
  18. }
  19. // 工厂接口
  20. interface IFactory1 {
  21.         public IProduct1 creadteProduct1();
  22.         public IProduct2 creadteProduct2();
  23. }

  24. // 产品类
  25. class Product1 implements IProduct1 {

  26.         @Override
  27.         public void show() {
  28.                 System.out.println("第一型号产品");
  29.         }

  30. }

  31. class Product2 implements IProduct2 {

  32.         @Override
  33.         public void show() {
  34.                 System.out.println("第二型号产品");
  35.         }

  36. }

  37. // 工厂类
  38. class Factory1 implements IFactory1 {

  39.         @Override
  40.         public IProduct1 creadteProduct1() {

  41.                 return new Product1();
  42.         }

  43.         @Override
  44.         public IProduct2 creadteProduct2() {

  45.                 return new Product2();
  46.         }

  47. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马