天天看点

.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,如需转载请自行联系原作者

继续阅读