設計模式-簡單工廠模式

最近在看大話設計模式,一直都把裏面的代碼都本身親手敲一遍去理解這些設計模式的含義,並且都在作着筆記,可是尋思着。應該拿出來和你們一塊兒交流共享,更但願你們可以指出不足。因此打算把這些東西拿出來你們一塊兒點評點評。設計模式

以後的內容都純屬我的理解,但願不會誤導別人。ide

今天先說說第一個,簡單工廠模式。學習

咱們舉個簡單的例子,不少人再講簡單工廠模式的時候相比都是會拿這個案例來作例子,計算器。spa

咱們設計一個簡單的計算器,只須要實現加減乘除這四個功能便可。設計

對於面向過程的思惟來看,加減乘除無非是四個方法,咱們寫好這幾個方法,而後傳入參數,獲取返回值便可。對象

可是咱們若是用面向對象的思想來看,加減乘除其實都是一個對象,而這個對象的父類,其實就是 運算(Operation) 。blog

因此咱們能夠定一個抽象類,讓加減乘除都來繼承這個父類(Operation)在父類中咱們給出一個方法,就叫作OperationNum吧。繼承

參數兩個,分別是要計算的兩個數,返回值 返回計算後的結果。string

加減乘除繼承了這個父類,而且實現具體的計算方法。這時候,咱們怎麼來用簡單工廠呢?it

咱們創建一個工廠靜態類,這個類中有一個靜態方法,參數是運算符,

根據用戶輸入的運算符,咱們來在工廠產生相對應的子類,而後以父類的姿態返回他,而後客戶端代碼只須要調用這個父類對象的OperationNum方法便可。

這裏涉及到里氏轉換原則,里氏轉換原則以下:
1.子類對象能夠直接賦值給父類變量
2.父類對象能夠強制類型轉化爲【對應的】 子類對象(重要)
子類擴展的方法和屬性 轉換爲父類時候 父類訪問不到,可是再強制轉換爲對應的子類時候會再次顯示。由於在轉換父類的時候被隱藏了
紅薯的例子,把紅薯裝在一個食品盒子裏,雖然從外觀上發生了變化,可是本質它仍是一個紅薯。當咱們拆開這個食品盒子,獲得的也只能是紅薯而不多是其餘的食物。
至關於打一個包 本質沒有變化

下面給出一個圖,來幫助你們理解這個簡單

下面再給出一些代碼幫助你們理解

//抽象父類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 計算器抽象
{
    abstract class Operation
    {
       public abstract int Run(int num1, int num2);
    }
}

 

//加減乘除子類,只給出一個方便理解
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 計算器抽象
{
    class Cut:Operation
    {
        public override int Run(int num1, int num2)
        {
            return num1 - num2;
        }
    }
}

 

//工廠類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 計算器抽象
{
    class FactoryClass
    {
        static Operation op = null;
        public static Operation Panduan(string  mark)
        {
            switch (mark)
            {
                case "+": op = new Add(); break;
                case "-": op = new Cut(); break;
                case "*": op = new Ride(); break;
                case "/": op = new Division(); break;
                default :;break;
            }
            return op;
 
        }
    }
}

 

//客戶端代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 計算器抽象
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("請輸入第一個數:");
            int num1 = int.Parse(Console.ReadLine());
            Console.WriteLine("請輸入第二個數:");
            int num2 = int.Parse(Console.ReadLine());
            Console.WriteLine("請輸入運算符:");
            string mark = Console.ReadLine();
            Operation opc = FactoryClass.Panduan(mark);
            if (opc != null)
            {
                Console.WriteLine(opc.Run(num1, num2));
            }
            else
            {
                Console.WriteLine("無效的運算符!");
 
            }
            Console.ReadKey();
        }
    }
}

 本人尚在學習階段,但願有寫的很差的地方,你們指正。

相關文章
相關標籤/搜索