工廠方法模式
- 工廠模式(Factory Pattern)是 Java 中最常用的設(shè)計模式之一。這種類型的設(shè)計模式屬于創(chuàng)建型模式细办,它提供了一種創(chuàng)建對象的最佳方式橙凳。
- 在工廠模式中,我們在創(chuàng)建對象時不會對客戶端暴露創(chuàng)建邏輯,并且是通過使用一個共同的接口來指向新創(chuàng)建的對象岛啸。
創(chuàng)建業(yè)務(wù)邏輯接口
public interface Product {
void creatProduct();
}
實現(xiàn)業(yè)務(wù)邏輯接口
public class HighProduct implements Product {
@Override
public void creatProduct() {
System.out.println("創(chuàng)建一個高等級的項目");
}
}
public class LowProduct implements Product {
@Override
public void creatProduct() {
System.out.println("創(chuàng)建一個低等級的項目");
}
}
創(chuàng)建業(yè)務(wù)工廠 根據(jù)不同的邏輯返回不同的實例
public class ProductFactory {
public Product creatProductLevel(String level) {
if (level.equals("high")) {
return new HighProduct();
} else if (level.equals("low")) {
return new LowProduct();
}
return null;
}
}
測試
ProductFactory productFactory = new ProductFactory();
Product high = productFactory.creatProductLevel("high");
high.creatProduct();
Product low = productFactory.creatProductLevel("low");
low.creatProduct();
輸出
創(chuàng)建一個高等級的項目
創(chuàng)建一個低等級的項目