設計模式 工廠模式 抽象工廠模式

2021-10-04 11:50:51 字數 3835 閱讀 3149

建立物件時不會對客戶暴露建立邏輯,並且通過使用乙個共同的介面來指向建立的物件。

sept1 建立乙個公共介面,將要對外開放的方法在這裡定義。

sept2 建立實現介面的類,用即實現對外開放的類的方法

sept3 建立工廠,提供乙個get方法,這個方法提供返回實現類的物件(建立選擇)

sept4 使用,建立工廠物件,使用工廠中的物件,來獲取對外開放的方法(使用選擇)

/** @author: xuandc

* @time : 2020-03-27

* @see: 工廠模式

* */

public inte***ce

shape

實現類1

/** @author: xuandc

* @time : 2020-03-27

* @see: 工廠模式

* */

public class

circleimplements

shape

public  void

dd()}

實現類2 /*

* @author:xuandc

* @time :2020-03-27

* @see: 介面實現類 square

* */

public class

squareimplements

shape }

實現類3

/** @author : xuandc

* @time: 2020-03-27

* @see:工廠模式實現類

* */

public class

rectangieimplements

shape }

工廠類/*

* @author :xuandc

* @time :2020-03-27

* @see: 建立乙個shape工廠類

* */

public class

shapefactory

if

(shapetype.equalsignorecase("circle"

))else if

(shapetype.equalsignorecase("rectangie"

))else if

(shapetype.equalsignorecase("square"

))return null;}

} 工廠使用

/** @author: xuandc

* @time : 2020-03-27

*/public class

factorypatterndemo }

抽象工廠模式是圍繞乙個超級工廠建立其它工廠。是其它工廠的工廠;

在抽象工廠模式中,介面負責建立相關物件的工廠,而不是明確指定它們的類。每個工廠可以按照工廠模式提供物件。

即將每個工廠抽象到乙個抽象類(相當於工廠中的介面)中

然後在建立乙個工廠創造,即返回例項化工廠類的(工廠模式中是例項化實現類)。

呼叫,建立抽象工廠型別的生產工廠器物件,獲取相應工廠物件(工廠物件選擇)

public inte***ce

shape   //形狀介面

public inte***ce

color          //顏色介面

public class

circleimplements

shape

public  void

dd()}

public class

squareimplements

shape }

public class

redimplements

color }

public class

blueimplements

color }

工廠1    顏色工廠

public class

colo***ctoryextends

abstractfactory

if

(color.equalsignorecase("red"

))else if

(color.equalsignorecase("green"

))else if

(color.equalsignorecase("blue"

))return null

;}@override

public

shape getshape(string shape) }

工廠2   形狀工廠

public class

shapefactoryextends

abstractfactory

@override

public

shape getshape(string shapetype)

if

(shapetype.equalsignorecase("circle"

))else if

(shapetype.equalsignorecase("rectangle"

))else if

(shapetype.equalsignorecase("square"

))return null;}

} public abstract class

abstractfactory

public class

factoryproducerelse if

(choice.equalsignorecase("color"

))return null;}

} public class

abstractfactorydemo

}

設計模式(簡單工廠模式 工廠模式 抽象工廠模式)

當邏輯較為簡單時,可以直接建立對應的類。如下 include using namespace std class class banana class pear intmain 通過此 可以發現,使用者直接與客戶接觸,違背了dip 依賴倒轉 原則,過於麻煩,所以引出簡單工廠模式。include us...

抽象工廠模式 常用設計模式 抽象工廠模式

提供乙個建立一系列相關或相互依賴物件的介面,而無需指定它們具體的類。在工廠方法模式中,我們的具體建立者每次使用都只能建立乙個同型別的物件,假如我們現在需要的是多個不同型別的物件,工廠方法就滿足不了需求了。這時我們可以把多個工廠方法組合到乙個類,這就是抽象工廠模式,它就是專門用來建立多個產品,也可以說...

抽象工廠模式 設計模式(九) 抽象工廠模式

提供乙個為建立一組相關或相互依賴物件的介面,且無須指定它們的具體類。它屬於建立型模式。在抽象工廠模式中,每個具體工廠都提供了多個用於建立多種不同型別具體物件的方法,這些不同型別的物件都存在乙個共同的屬性,構成乙個族。上篇文章設計模式 八 工廠方法模式說到工廠方法模式中只考慮某一類產品的生產,例如可樂...