码迷,mamicode.com
首页 > 其他好文 > 详细

简单工厂模式

时间:2017-03-04 19:06:05      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:[]   开发   接口   val   base   div   ace   csdn   new   

完整解决方案

       为了将Chart类的职责分离,同时将Chart对象的创建和使用分离,Sunny软件公司开发人员决定使用简单工厂模式对图表库进行重构,重构后的结构如图2所示:

技术分享

图2 图表库结构图

       在图2中,Chart接口充当抽象产品类,其子类HistogramChart、PieChart和LineChart充当具体产品类,ChartFactory充当工厂类。完整代码如下所示:

[java] view plain copy
 
  1. //抽象图表接口:抽象产品类  
  2. interface Chart {  
  3.     public void display();  
  4. }  
  5.   
  6. //柱状图类:具体产品类  
  7. class HistogramChart implements Chart {  
  8.     public HistogramChart() {  
  9.         System.out.println("创建柱状图!");  
  10.     }  
  11.       
  12.     public void display() {  
  13.         System.out.println("显示柱状图!");  
  14.     }  
  15. }  
  16.   
  17. //饼状图类:具体产品类  
  18. class PieChart implements Chart {  
  19.     public PieChart() {  
  20.         System.out.println("创建饼状图!");  
  21.     }  
  22.       
  23.     public void display() {  
  24.         System.out.println("显示饼状图!");  
  25.     }  
  26. }  
  27.   
  28. //折线图类:具体产品类  
  29. class LineChart implements Chart {  
  30.     public LineChart() {  
  31.         System.out.println("创建折线图!");  
  32.     }  
  33.       
  34.     public void display() {  
  35.         System.out.println("显示折线图!");  
  36.     }  
  37. }  
  38.   
  39. //图表工厂类:工厂类  
  40. class ChartFactory {  
  41.     //静态工厂方法  
  42.     public static Chart getChart(String type) {  
  43.         Chart chart = null;  
  44.         if (type.equalsIgnoreCase("histogram")) {  
  45.             chart = new HistogramChart();  
  46.             System.out.println("初始化设置柱状图!");  
  47.         }  
  48.         else if (type.equalsIgnoreCase("pie")) {  
  49.             chart = new PieChart();  
  50.             System.out.println("初始化设置饼状图!");  
  51.         }  
  52.         else if (type.equalsIgnoreCase("line")) {  
  53.             chart = new LineChart();  
  54.             System.out.println("初始化设置折线图!");              
  55.         }  
  56.         return chart;  
  57.     }  
  58. }  

       编写如下客户端测试代码:

[java] view plain copy
 
  1. class Client {  
  2.     public static void main(String args[]) {  
  3.         Chart chart;  
  4.         chart = ChartFactory.getChart("histogram"); //通过静态工厂方法创建产品  
  5.         chart.display();  
  6.     }  
  7. }  

       编译并运行程序,输出结果如下:

 

创建柱状图!

初始化设置柱状图!

显示柱状图!

 

       在客户端测试类中,我们使用工厂类的静态工厂方法创建产品对象,如果需要更换产品,只需修改静态工厂方法中的参数即可,例如将柱状图改为饼状图,只需将代码:

 

chart = ChartFactory.getChart("histogram");

 

       改为:

 

chart = ChartFactory.getChart("pie");

 

       编译并运行程序,输出结果如下:

 

创建饼状图!

初始化设置饼状图!

显示饼状图!

 


【作者:刘伟 http://blog.csdn.net/lovelion

简单工厂模式

标签:[]   开发   接口   val   base   div   ace   csdn   new   

原文地址:http://www.cnblogs.com/BrokenIce/p/6501947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!