黑马程序员技术交流社区

标题: 简单工厂模式 [打印本页]

作者: 小车车    时间: 2015-6-4 21:45
标题: 简单工厂模式
  1. //面向接口编程
  2. //1.简单工厂模式。假如让computer类组合一个printer对象,如果有一天系统需要重构,需要使用Butterpriner来代替printer,这就需要
  3. //打开computer类源代码进行修改。这样导致很不方便。
  4. //为了避免这个问题,工厂模式建议让computer类组合一个output类型对象,将computer类与printer类完全分离。
  5. public class Computer{
  6.         private Output out;
  7.         public Computer(Output out){
  8.                 this.out=out;
  9.         }
  10.         //定义一个模拟获取字符串输入的方法
  11.         public void keyIn(String msg){
  12.                 out.getData(msg);
  13.         }
  14.         public void print(){
  15.                 out.out;
  16.         }
  17.         }

  18. public class OutputFactory{
  19.         public Output getOutput(){
  20.                 return new Printer();
  21.         }
  22.         public static void main(String[] args){
  23.                 OutputFactory of=new  OutputFactory();
  24.                 Computer c= new Computer(of.getOutput());
  25. }
  26. }

  27. public class BetterPrinter implements Output{
  28.        
  29. }
  30. //上面的BetterPrinter类实现了Output接口,因此也可当成output对象使用,于是只要把outputFactory工厂类的getoutput()方法中代码改为:
  31. //return new BetterPrinter();
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2