天天看點

.NET 設計模式初探

最近,正在抓緊時間看.NET的視訊,期末考試結束了,整個人也散了,找不到什麼正經的事情幹,沒事就在實驗室泡着,學習一下各方各面的知識,拓展一下思路和知識,感覺不錯,呵呵。

    下面是在聽WebCast的設計模式的視訊時,實作的例子,比較簡單,具體對模式的了解和應用還很需要深入……

using System;

namespace CSDesignPattern

{

 public enum UserType{Employee=0, Sales=1, Guest=2};//聲明一個枚舉,三種類型的使用者

 public class User

 {

  protected string level = "Z"; //權限級别

  public string GetLevel()      //得到該使用者權限,預設為Z

  {

   return level;

  }

 }

 public class Employee : User //繼承,重新設定級别

  public Employee()

   level = "A";

 public class Sales : User

  public Sales()

   level = "B";

 public class Guest : User

  public Guest()

   level = "C";

 public class FactoryCreator

  public FactoryCreator(){}

  public static User  CreateUser(UserType userType)  //根據使用者類型初始化不同的使用者

  {  

   User u = null;

   switch(userType) 

   {

    case UserType.Employee:

     u = new Employee();

     break;

    case UserType.Sales:

     u = new Sales();

    case UserType.Guest:

     u = new Guest();

   };

   return u;

  static void Main(string[] args)

   Console.WriteLine("Input Type");

   UserType t = (UserType)int.Parse(Console.ReadLine());

   User newUser = FactoryCreator.CreateUser(t);

   Console.WriteLine("Create an object:{0}" ,newUser.ToString());

   Console.WriteLine("Level = {0}",newUser.GetLevel());

   Console.ReadLine();

}

本文轉自 august 51CTO部落格,原文連結:http://blog.51cto.com/august/6903,如需轉載請自行聯系原作者

繼續閱讀