設計模式 簡單工廠模式

2021-08-01 09:14:20 字數 1893 閱讀 1651

簡單工廠模式又名靜態方法工廠模式,由乙個工廠物件決定建立哪乙個產品的例項 使用場景:客戶端需要建立物件,隱藏物件的建立過程,並且目標物件型別數量不是很多的時候,可以考慮使用簡單工廠模式 product 產品的通用介面,用來定義產品的行為 concreteproduct 具體的產品,實現了product介面creater 工廠類,通過factory來建立物件優點:分工明確,各司其職客戶端不再建立物件,而是把建立物件的職責交給了具體的工廠去建立使抽象與實現分離,客戶端不知道具體的實現過程具名工廠函式,更能體現**的含義缺點:工廠的靜態方法無法被繼承**維護不易,要是物件很多的話,工廠類會很龐大違反開閉原則,如果有新的產品加入系統中就要修改工廠類

package com.lantier.xxb_student.drawlayerlayout.iphone;

/*** created by xxb_student on 2017/5/20.

*/public inte***ce iphone

package com.lantier.xxb_student.drawlayerlayout.iphone;

import android.util.log;

/*** created by xxb_student on 2017/5/20.

*/public class iphone4s implements iphone

@override

public void

sendmessage()

@override

public void

getnetwork()

}

package com.lantier.xxb_student.drawlayerlayout.iphone;

import android.util.log;

/*** created by xxb_student on 2017/5/20.

*/public class iphone5s implements

iphone

@override

public void

sendmessage()

@override

public void

getnetwork()

}

package com.lantier.xxb_student.drawlayerlayout.iphone;

/*** created by xxb_student on 2017/5/20.

*/public final class iphonefactory

iphone iphone = null;

if (type.equals("iphone4s")) else if (type.equals("iphone5s"))

return

iphone;}

}

最後的log:

iphone iphone4s = iphonefactory.createiphone("iphone4s");

iphone4s.sendmessage();

iphone iphone5s = iphonefactory.createiphone("iphone5s");

iphone5s.call();

05-20 11:45:50.554 20843-20843/com.lantier.xxb_student.drawlayerlayout d/iphone4s: ---->>sendmessage:iphone4s 

05-20 11:45:50.555 20843-20843/com.lantier.xxb_student.drawlayerlayout d/iphone5s: ---->>call: iphone5s

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

一 簡單工廠 定義 簡單工廠模式 factory pattern 屬於類的創新型模式,又叫靜態工廠方法模式 static factorymethod pattern 是通過專門定義乙個類來負責建立其他類的例項,被建立的例項通常都具有共同的父類。特點 工廠類直接實現,乙個產品介面,乙個工廠類可以產生多...

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

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

設計模式 簡單工廠設計模式

請用任意一種物件導向語言實現計算器控制台程式,要求輸入兩個數和運算符號,得到結果。operation運算類 public class operation set public double numberb set public virtual double getresult 加減乘除類 using...