.NET 设计模式初探

本文介绍了一个简单的C#工厂模式实例,通过创建不同类型的用户并设置相应的权限等级,展示了如何使用工厂模式来实例化不同类别的对象。
最近,正在抓紧时间看.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();
     break;
    case UserType.Guest:
     u = new Guest();
     break;
   };
   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,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值