【抽象工厂模式】Abstract Factory Design

2016-02-01  本文已影响119人  jackLee
Abstract_Factory.png

抽象工厂模式

Abstract_Factory_example.png

创建抽象工厂的步骤:

第一步:创建Super Classs 和 Sub Class:

--需要被Client大量使用的类和对象
--Super Class 可以为接口 ,抽象类或是正常的类
--Sub Class 实现或者继承自父类,然后个性化自己

public abstract class Computer {

public abstract String getRAM();
public abstract String getHDD();
public abstract String getCPU();
  
@Override
public String toString(){
    return "RAM= "+this.getRAM()+", HDD="+this.getHDD()+", CPU="+this.getCPU();
}

}
</code>

public class PC extends Computer {

private String ram;
private String hdd;
private String cpu;
  
public PC(String ram, String hdd, String cpu){
    this.ram=ram;
    this.hdd=hdd;
    this.cpu=cpu;
}
@Override
public String getRAM() {
    return this.ram;
}

@Override
public String getHDD() {
    return this.hdd;
}

@Override
public String getCPU() {
    return this.cpu;
}

}
</code>

public class Server extends Computer {

private String ram;
private String hdd;
private String cpu;
  
public Server(String ram, String hdd, String cpu){
    this.ram=ram;
    this.hdd=hdd;
    this.cpu=cpu;
}
@Override
public String getRAM() {
    return this.ram;
}

@Override
public String getHDD() {
    return this.hdd;
}

@Override
public String getCPU() {
    return this.cpu;
}

}
</code>

第二步:创建Abstract Factory Class

第三步:创建个Sub Class 的工厂方法

import com.journaldev.design.model.Computer;
import com.journaldev.design.model.PC;

public class PCFactory implements ComputerAbstractFactory {

private String ram;
private String hdd;
private String cpu;
 
public PCFactory(String ram, String hdd, String cpu){
    this.ram=ram;
    this.hdd=hdd;
    this.cpu=cpu;
}
@Override
public Computer createComputer() {
    return new PC(ram,hdd,cpu);
}

}
Similarly
</code>
同样的我们再创建 ServerFactory.java

import com.journaldev.design.model.Computer;
import com.journaldev.design.model.Server;

public class ServerFactory implements ComputerAbstractFactory {

private String ram;
private String hdd;
private String cpu;
 
public ServerFactory(String ram, String hdd, String cpu){
    this.ram=ram;
    this.hdd=hdd;
    this.cpu=cpu;
}
 
@Override
public Computer createComputer() {
    return new Server(ram,hdd,cpu);
}

}
</code>
.....根据需求我们还能创建很多的Factory类.....

第四步:创建一个 consumer class 作为入口供Client调用

import com.journaldev.design.model.Computer;

public class ComputerFactory {
public static Computer getComputer(ComputerAbstractFactory factory){
return factory.createComputer();
}
}
</code>

第五步:测试程序

一张模型图

class diagram.png

总结&&抽象工厂模式的好处

上一篇下一篇

猜你喜欢

热点阅读