public Computer(Output output) { this.output = output; }
public void keyIn(String msg) { output.getData(msg); }
public void print(){ output.out(); } }
5、现在可以进行打印了:
1 2 3 4 5 6 7 8 9 10 11 12 13
public class main { public static void main(String[] args) { //创建一个工厂 OutputFactory of = new OutputFactory(); //从工厂中生产一件Output标准的产品 Computer computer = new Computer(of.getOutput()); //调用 computer.keyIn("sssss"); computer.print(); }
private List<String> buffer = new ArrayList<>(); @Override public void out() { System.out.println("这是一个性能更好的sony的打印机在执行out方法"+buffer.get(0)); }
@Override public void getData(String data) { System.out.println("这是一个性能更好的sony的打印机在执行out方法"+buffer.add(data)); } }
修改工厂的生产方法,让其生产BetterFactory产品:
1 2 3 4 5
public class OutputFactory { public Output getOutput() { return new BetterPrinter(); } }
打印接口:
1 2 3 4 5 6 7 8 9 10 11 12 13
public class main { public static void main(String[] args) { //创建一个工厂 OutputFactory of = new OutputFactory(); //从工厂中生产一件Output标准的产品 Computer computer = new Computer(of.getOutput()); //调用 computer.keyIn("sssss"); computer.print(); }
public Computer(Output output) { this.output = output; }
public void keyIn(String msg) { output.getData(msg); }
public void print(){ output.out(); }
public static void main(String[] args) { OutputFactory of = new PrinterFactory(); Computer computer = new Computer(of.getOutput()); computer.keyIn("this is Bob"); computer.print(); } }
运行程序后:
1 2 3
这是一个性能一般的sony打印机在输入数据this is Bob 这是一个性能一般的sony打印机在打印。。this is Bob
public class OutputFactoryFactory { public static OutputFactory getOutputFactory(String type) { if (type.equalsIgnoreCase("better")) { return new BetterPrinterFactory(); }else { return new PrinterFactory(); } } }
public Computer(Output output) { this.output = output; }
public void keyIn(String msg) { output.getData(msg); }
public void print(){ output.out(); }
public static void main(String[] args) { // OutputFactory of = new PrinterFactory(); OutputFactory of = OutputFactoryFactory.getOutputFactory("better"); Computer computer = new Computer(of.getOutput()); computer.keyIn("this is Bob"); computer.print(); } }