二十三種設計模式之抽象工廠模式
抽象工廠模式
用于生産不同産品族的全部産品(對于增加新的産品,無能為力,支援增加産品族)
抽象工廠模式是對同種業務,不同情況
應用場景
- JDK 中 Calendar 的 getInstance() 方法
- JDBC 中 Connection 對象的擷取
- Spring 中 IOC 容器建立管理 Bean 對象
- XML 解析時的 DocumentBuiulderFactory 建立解析器對象
- 反射中 Class 對象的 newInstance()
優勢劣勢
Engine 接口及其實作類
package factory.abstra;
/**
* @author SIMBA1949
* @date 2019/6/6 11:21
*/
public interface Engine {
void speedRatio();
}
class LowEngine implements Engine{
public void speedRatio() {
System.out.println("低端引擎,轉速慢");
}
}
class LuxuryEngine implements Engine{
public void speedRatio() {
System.out.println("高端引擎,轉速快");
}
}
Seat 接口及其實作類
package factory.abstra;
/**
* @author SIMBA1949
* @date 2019/6/6 11:22
*/
public interface Seat {
void function();
}
class LowSeat implements Seat{
public void function() {
System.out.println("低端座椅");
}
}
class LuxurySeat implements Seat{
public void function() {
System.out.println("高端座椅");
}
}
Tire 接口及其實作類
package factory.abstra;
/**
* @author SIMBA1949
* @date 2019/6/6 11:22
*/
public interface Tire {
void durability();
}
class LowTire implements Tire{
public void durability() {
System.out.println("低端輪胎");
}
}
class LuxuryTire implements Tire{
public void durability() {
System.out.println("高端輪胎");
}
}
抽象工廠 及其實作類
package factory.abstra;
/**
* @author SIMBA1949
* @date 2019/6/6 11:26
*/
public interface ProductsFactory {
Engine createEngine();
Seat createSeat();
Tire createTire();
}
class LowProductFactory implements ProductsFactory {
public Engine createEngine() {
return new LowEngine();
}
public Seat createSeat() {
return new LowSeat();
}
public Tire createTire() {
return new LowTire();
}
}
class LuxuryProductFactory implements ProductsFactory {
public Engine createEngine() {
return new LuxuryEngine();
}
public Seat createSeat() {
return new LuxurySeat();
}
public Tire createTire() {
return new LuxuryTire();
}
}
Client 測試
package factory.abstra;
/**
* @author SIMBA1949
* @date 2019/6/6 11:29
*/
public class AbstractFactoryClient {
public static void main(String[] args) {
Engine lowEngine = new LowProductFactory().createEngine();
Seat lowSeat = new LowProductFactory().createSeat();
Tire lowTire = new LowProductFactory().createTire();
Engine luxuryEnginer = new LuxuryProductFactory().createEngine();
Seat luxurySeat = new LuxuryProductFactory().createSeat();
Tire luxuryTire = new LuxuryProductFactory().createTire();
}
}