工厂类生产output实例
public class OutputFactory {
public Output getOutput(){
return new Printer();
}
}
Computer类,可以利用工厂得到output实例
public class Computer {
private Output out;
public Computer(Output out){
this.out = out;
}
public void keyIn(String msg){
out.getData(msg);
}
public void print(){
out.out();
}
public static void main(String args[]){
OutputFactory of = new OutputFactory();
Computer computer = new Computer(of.getOutput());
computer.keyIn("output success");
computer.print();
}
}
Output规范接口
public interface Output {
public void out();
public void getData(String msg);
}
Output实现类
public class Printer implements Output{
String msg;
public void out() {
System.out.println("the output: " + msg);
}
public void getData(String msg) {
this.msg = msg;
}
}