抽象工厂具象化

在简单工厂设计模式之后还有一个抽象工厂设计模式。

上次在工厂里面吃了饺子,那么抽象工厂,我我们将换一种方式和大家见面,从我们日常最为常见的两大系统最为今天的切入点,

Win 和 Mac。这两大系统我想最为程序员的我们因该很是熟悉了吧,不论从系统到左面的设计风格两大系统都有着各自的亮点,

那么它们怎么会和我们今天要说的设计模式扯到一起呢?那么接下来我们就好好的说一下这个抽象工厂设计模式到底是个什么东西。

首先大家有没有看过我之前的饺子馆的博客,如果没有的话建议看一下,不看也关系 https://mp.youkuaiyun.com/mp_blog/creation/editor/145682283

在这篇博客中,我讲述了工厂设计模式关注的点在具体的产品,通过不同的条件,出来的都是具体的什么馅的饺子。那么今天我们

将从 两大系统来聊聊抽象工程,我们在聊抽象工厂的时候,因该把关注点转义,放到更高的抽象上面去,(系统),不看具体的实现,

只看最顶级的抽象,是不是都有着,各自的不同的系统级别的UI,要是理解了这一点的话,接下来就好理解了,Win 系统出来不同的系列,

和 Mac 系统出来的不同系列,都是抽象工厂的具体话,拿其中的一两个点说一下, Button 和 Text,用这两个,最为经典和常见的UI来通过,

代码具象化出来,看代码:

// 1. 抽象产品族
interface Button { void render(); }
interface TextBox { void display(); }

// 2. 具体产品族:Windows 风格
class WinButton implements Button {
    @Override public void render() { System.out.println("Windows 风格按钮"); }
}
class WinTextBox implements TextBox {
    @Override public void display() { System.out.println("Windows 风格文本框"); }
}

// 3. 具体产品族:macOS 风格
class MacButton implements Button {
    @Override public void render() { System.out.println("macOS 风格按钮"); }
}
class MacTextBox implements TextBox {
    @Override public void display() { System.out.println("macOS 风格文本框"); }
}

// 4. 抽象工厂
interface GUIFactory {
    Button createButton();
    TextBox createTextBox();
}

// 5. 具体工厂
class WinFactory implements GUIFactory {
    @Override public Button createButton() { return new WinButton(); }
    @Override public TextBox createTextBox() { return new WinTextBox(); }
}

class MacFactory implements GUIFactory {
    @Override public Button createButton() { return new MacButton(); }
    @Override public TextBox createTextBox() { return new MacTextBox(); }
}

// 使用
public class Application {
    private GUIFactory factory;
    
    public Application(GUIFactory factory) { this.factory = factory; }
    
    void buildUI() {
        Button button = factory.createButton();
        TextBox textBox = factory.createTextBox();
        button.render();
        textBox.display();
    }
}

// 根据系统类型选择工厂
GUIFactory factory = System.getProperty("os.name").contains("Win") 
                     ? new WinFactory() : new MacFactory();
new Application(factory).buildUI();

这个地方,不是马上能理解和看懂的也没有关系,需要想一想,应该很快就能理解,仅仅是自己的一些总结和想法,有问题欢迎大家指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值