抽象工厂模式

54 阅读1分钟

抽象工厂模式

抽象工厂模式,封装一组具有共同主题的个别工厂而无需指定它们的具体类。

案例:

假设正在开发一个UI库,需要根据不同的操作系统(如Windows和Mac)来创建不同风格的UI元素(如按钮和复选框)。可以使用抽象工厂模式来实现这个需求。

// 抽象产品:按钮
interface Button {
    paint(): void;
}
​
// 具体产品:Windows按钮
class WindowsButton implements Button {
    paint() {
        console.log("Rendering a button in Windows style.");
    }
}
​
// 具体产品:Mac按钮
class MacButton implements Button {
    paint() {
      console.log("Rendering a button in Mac style.");
    }
}
​
// 抽象产品:复选框
interface Checkbox {
    paint(): void;
}
​
// 具体产品:Windows复选框
class WindowsCheckbox implements Checkbox {
    paint() {
      console.log("Rendering a checkbox in Windows style.");
    }
}
​
// 具体产品:Mac复选框
class MacCheckbox implements Checkbox {
    paint() {
      console.log("Rendering a checkbox in Mac style.");
    }
}
​
// 抽象工厂
interface GUIFactory {
    createButton(): Button;
    createCheckbox(): Checkbox;
}
​
// 具体工厂:Windows工厂
class WindowsFactory implements GUIFactory {
    createButton(): Button {
        return new WindowsButton();
    }
​
    createCheckbox(): Checkbox {
        return new WindowsCheckbox();
    }
}
​
// 具体工厂:Mac工厂
class MacFactory implements GUIFactory {
    createButton(): Button {
        return new MacButton();
    }
​
    createCheckbox(): Checkbox {
        return new MacCheckbox();
    }
}
​
function buildUI(factory: GUIFactory) {
    const button = factory.createButton();
    const checkbox = factory.createCheckbox();
​
    button.paint();
    checkbox.paint();
}
​
// 假设根据运行时环境选择工厂
const currentOS = "Windows"; // 或者 "Mac"
const factory = currentOS === "Windows" ? new WindowsFactory() : new MacFactory();
buildUI(factory);
​

客户端代码可以根据不同的环境需求,使用对应的工厂来创建UI元素。