Net設計模式執行個體之簡單原廠模式(Simple Factory Pattern)

來源:互聯網
上載者:User

標籤:over   解決   result   bre   strong   example   body   public   com   

一、簡單原廠模式簡介(Bref Introduction)

       簡單原廠模式(Simple Factory Pattern)的優點是,工廠類中包含了必要的邏輯判斷,根據用戶端的選擇條件動態執行個體化相關的類,對於用戶端來說,去除了與具體產品的依賴

二、解決的問題(What To Solve)

       客戶執行個體化對象時不需要關心該對象是由哪個子類執行個體化的。

三、簡單原廠模式分析(Analysis)1、簡單原廠模式結構

 

IProduct介面:抽象產品類

ConcreteProduct:產品類的具體實現

Simple Factory簡單工廠類

四.執行個體分析(Example)1、情境

一個簡單計算機,具有簡單的加操作和減操作。結構如所示

 

 

SimpleFactory:簡單工廠類。

Operation:抽象操作類

AddOperation:加法操作

SubOperation:減法操作

2、代碼

 

1、抽象操作類Operation,及其具體實作類別AddOperation、SubOperation

/// <summary>

/// 抽象操作類

/// </summary>

public abstract class Operation

{

    public int numberA;

    public int numberB;

    public abstract int GetResult();

}

/// <summary>

/// 加法操作

/// </summary>

public class AddOperation : Operation

{

    public override int GetResult()

    {

       return (this.numberA + this.numberB);

    }

}

/// <summary>

/// 減法操作

/// </summary>

public class SubOperation : Operation

{

    public override int GetResult()

    {

        return (this.numberA - this.numberB);

    }

}

 

 

 

2、簡單工廠類SimpleFactory

/// <summary>

/// 簡單工廠類

/// </summary>

public class SimpleFactory

{

    public static Operation CreateOperation(string operation)

    {

        Operation o = null;

 

        switch (operation)

        {

            case "+":

                o = new AddOperation();

                break;

            case "-":

                o = new SubOperation();

                break;

        }

        return o;

    }

}

 

 

 

3、用戶端代碼

static void Main(string[] args)

{

    Operation operation1 = SimpleFactory.CreateOperation("+");

    operation1.numberA = 10;

    operation1.numberB = 20;

    Console.WriteLine("{0}+{1}={2}", operation1.numberA, operation1.numberB, operation1.GetResult());

 

    Operation operation2 = SimpleFactory.CreateOperation("-");

    operation2.numberA = 10;

    operation2.numberB = 20;

    Console.WriteLine("{0}-{1}={2}", operation2.numberA, operation2.numberB, operation2.GetResult());

 

    Console.Read();

}

 

 

3、執行個體運行結果 

 

五、總結(Summary)

簡單原廠模式是比較簡單的一種設計模式,本文對此模式的概念及其設計結構圖簡單地進行了描述,最後以一個計算機的執行個體進行了說明。

 

轉載自:http://www.cnblogs.com/ywqu/archive/2010/01/06/1640026.html

Net設計模式執行個體之簡單原廠模式(Simple Factory Pattern)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.