依然是简单工厂模式中的打印机案例,不过这里把工厂设计成接口,让不同的工厂生产不同的打印机,再抽象出一个生产工厂的工厂
打印机接口
package com.meteor.design_pattern.abstract_factory;
/**
* Created by Meteor on 2016/3/27.
*/
public interface Output {
void out();
void getData(String msg);
}
打印机A 实现打印机接口
package com.meteor.design_pattern.abstract_factory;
/**
* Created by Meteor on 2016/3/27.
*/
public class PrinterA implements Output{
private String msg;
public void out() {
System.out.println(this.msg);
}
public void getData(String msg) {
this.msg = msg;
}
}
打印机B 实现打印机接口
package com.meteor.design_pattern.abstract_factory;
/**
* Created by Meteor on 2016/3/27.
*/
public class PrinterB implements Output{
private String msg;
public void out() {
System.out.println("loop print:");
for (int i = 0; i <5; i++) {
System.out.println(this.msg);
}
}
public void getData(String msg) {
this.msg = msg;
}
}
打印机工厂接口
package com.meteor.design_pattern.abstract_factory;
/**
* Created by Meteor on 2016/3/27.
*/
public interface OutputFactory {
Output getOutput();
}
生产打印机A的工厂实现
package com.meteor.design_pattern.abstract_factory;
/**
* Created by Meteor on 2016/3/27.
*/
public class PrintAFactory implements OutputFactory{
public Output getOutput() {
return new PrinterA();
}
}
生产打印机B的工厂实现
package com.meteor.design_pattern.abstract_factory;
/**
* Created by Meteor on 2016/3/27.
*/
public class PrintBFactory implements OutputFactory{
public Output getOutput() {
return new PrinterB();
}
}
生产打印机工厂的工厂
package com.meteor.design_pattern.abstract_factory;
/**
* Created by Meteor on 2016/3/27.
*/
public class OutputFactoryFactory {
public static OutputFactory getOutputFactory(String type){
if("A".equals(type)){
return new PrintAFactory();
}else{
return new PrintBFactory();
}
}
}
计算机模拟打印
package com.meteor.design_pattern.abstract_factory;
import com.meteor.design_pattern.abstract_factory.OutputFactory;
/**
* Created by Meteor on 2016/3/27.
*/
public class Computer {
private Output out;
public Computer(Output out){
this.out = out;
}
public void out(){
out.out();
}
public void getData(String msg){
out.getData(msg);
}
public static void main(String[] args) {
//由用户自己选择使用哪家工厂生产的打印机,而不必关心打印机是如何生产的
OutputFactory outPutFactory = OutputFactoryFactory.getOutputFactory("B");
Computer computer = new Computer(outPutFactory.getOutput());
computer.getData("Hello World");
computer.out();
}
}