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

设计模式之静态工厂模式

时间:2015-09-13 13:14:38      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

public interface Printer {
  public abstract void open();
  public abstract void close();
  public abstract void print();
}

public class HPPrinter implements Printer {
  @Override
  public void open() {
    System.out.println("HPPrinter open");
  }
  @Override
  public void close() {
    System.out.println("HPPrinter close");
  }
  @Override
  public void print() {
    System.out.println("HPPrinter print");
  }
}

public class HWPrinter implements Printer {
  @Override
  public void open() {
    System.out.println("HWPrinter open");
  }
  @Override
  public void close() {
    System.out.println("HWPrinter open");
  }
  @Override
  public void print() {
    System.out.println("HWPrinter open");
  }
}

public class FactoryPrinter {
  public static Printer getPrinter(int arg) {
  Printer printer = null;
  if(arg == 0) {
    printer = new HPPrinter();
  }
  else if(arg == 1) {
    printer = new HWPrinter();
  }
  return printer;
  }
}

public class Computer
{
      private Printer printer;
  public Computer(Printer printer)
  {
    this.printer = printer;
  }
  //定义一个模拟打印的方法
  public void print()
  {
    printer.print();
  }
}

public class Test {
  public static void main(String[] args) {
    Printer printer = null;
    int flag = 0;
    printer = FactoryPrinter.getPrinter(flag);
    Computer computer = new Computer(printer);
    computer.print();
  }
}

设计模式之静态工厂模式

标签:

原文地址:http://www.cnblogs.com/zhangkefan/p/4804587.html

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