7

工厂三兄弟之简单工厂模式(三)

 3 years ago
source link: https://blog.csdn.net/LoveLion/article/details/9300657
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

3 完整解决方案

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

图2 图表库结构图

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

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

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

创建柱状图!

初始化设置柱状图!

显示柱状图!

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

chart = ChartFactory.getChart("histogram");

chart = ChartFactory.getChart("pie");

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

创建饼状图!

初始化设置饼状图!

显示饼状图!

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK