Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 理解抽象工厂设计模式_Oop_Design Patterns - Fatal编程技术网

Oop 理解抽象工厂设计模式

Oop 理解抽象工厂设计模式,oop,design-patterns,Oop,Design Patterns,在抽象工厂设计模式中,一个类通过组合将对象实例化的责任委托给另一个对象 有人能举个例子来解释一下吗。我会告诉你一个传统的例子。假设您有一个UI库。它实现了不同的UI组件,如按钮、滑块、单选按钮等。您还希望这些组件具有不同的外观和感觉,例如银色、深色、浅色、windows等,gtk等。您可以使用一个抽象类,该类为每个组件的创建提供公共内容,子类继承自抽象并仅指定差异: class AbstractComponentFactory { public abstract Button crea

在抽象工厂设计模式中,一个类通过组合将对象实例化的责任委托给另一个对象


有人能举个例子来解释一下吗。

我会告诉你一个传统的例子。假设您有一个UI库。它实现了不同的UI组件,如按钮、滑块、单选按钮等。您还希望这些组件具有不同的外观和感觉,例如银色、深色、浅色、windows等,gtk等。您可以使用一个抽象类,该类为每个组件的创建提供公共内容,子类继承自抽象并仅指定差异:

class AbstractComponentFactory {

    public abstract Button createButton() {
        //implementation
    }

    public abstract Slider createSlider() {
        //implementation
    }
}

class SilverComponentFactory extends AbstractFactory {

    public Button createButton() {
        Button b = base.createButton();
        //customize the button
    }

    public Slider createSlider() {
        Slider b = base.createSlider();
        //customize the slider
    }

}


class WindowsComponentFactory extends AbstractFactory {

    public Button createButton() {
        Button b = base.createButton();
        //customize the button with windows look-and-feel
    }

    public Slider createSlider() {
        Slider b = base.createSlider();
        //customize the slider with windows look-and-feel
    }

}
现在,如果需要创建组件,可以动态更改抽象工厂的实现:

public void createUI(AbstractComponentFactory f) {
     Button b = f.createButton();
     Slider s = f.createSlider();
}

//..
createUI(new SilverComponentFactory());

是一个示例类图,我希望它不要那么复杂。

您指的是抽象类,还是抽象工厂模式?抽象工厂pattern@OP:您熟悉简单的工厂模式吗?抽象工厂(或多或少)是一个简单工厂,它生成一个可以生成具体类的简单工厂:)这就是我想在抽象工厂模式中理解的:一个类通过组合将对象实例化的责任委托给另一个对象。而在工厂中,模式使用继承并依赖子类来处理对象实例化。这里大家要解释的是抽象工厂和使用继承的工厂,那么这两种模式的区别在哪里呢@斯维科:区别在于抽象的另一层。根据对抽象工厂的理解,抽象工厂模式是在你有工厂可以创建一系列对象时使用的。而工厂类是抽象的。而在工厂的情况下,方法对工厂类进行抽象,并生成单个产品对象集。这就是我对工厂方法模式和抽象工厂模式的理解。如果我错了,请告诉我。而我的查询是关于组合和继承的。