抽象工厂模式:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。 工厂方法模式和抽象工厂模式基本类似,可以这么理解:当工厂只生产一个产品的时候,即为工厂方法模式,而工 厂如果生产两个或以上的商品即变为抽象工厂模式。 我们在抽象工厂接口中新增创建系统的方法,并由实例工厂类去实现。
类图可由下表示:
interface Computer{
public void printComputer();
}
class MacbookProComputer implements Computer{
public void printComputer(){
System.out.println("this is a mac");
}
}
class SurfaceBookComputer implements Computer{
public void printComputer(){
System.out.println("this is a Surface");
}
}
interface OperatingSystem {
void printSystem();
}
class MacOsSystem implements OperatingSystem {
public void printSystem() {
System.out.println("This is a mac os");
}
}
class Windows8System implements OperatingSystem {
public void printSystem() {
System.out.println("This is a window 8");
}
}
interface ProductionFactory{
Computer createComputer();
OperatingSystem createSystem();
}
class MCFactory implements ProductionFactory{
public Computer createComputer(){
return new MacbookProComputer();
}
public OperatingSystem createSystem(){
return new MacOsSystem();
}
}
class SurfFactory implements ProductionFactory{
public Computer createComputer(){
return new SurfaceBookComputer();
}
public OperatingSystem createSystem(){
return new Windows8System();
}
}
class Client{
public void buyComputer(Computer computer) {
computer.printComputer();
}
public void use(OperatingSystem s){
s.printSystem();
}
}
public class mytest{
public static void main(String[]args){
Client c=new Client();
ProductionFactory factory = new MCFactory();
// ComputerFactory factory = new SurfFactory();
Computer computer = factory.createComputer();
OperatingSystem system = factory.createSystem();
c.buyComputer(computer);
c.use(system);
}
}