原创作者: age0   阅读:1636次   评论:0条   更新时间:2011-06-01    
需求如下:
有这样一家超市,对顾客实行会员制,会员目前分为两个等级:金卡及银卡。
每次会员购物时,都会根据会员等级提供不同的折扣优惠和返点。

设计方案有三个:
1. 过程设计,用作对比
2. 过程式的OO设计,简单来说就是将过程设计中的函数封装到类里面
3. 标准的OO设计,封装、继承、多态、设计模式,能用的都用上

问题:
如果是你,你会采用哪种OO设计,或者有更好的设计?


过程式设计:
// client:

string id = input_id;

string type = GetMemberTypeByID();;

int discount = GetDiscountByType(type);;
int point = GetReturnPoint(type);;


// service:

string GetMemberTypeByID(string id);
{
	string type;
	
	// get type by id
	...
	
	return type;
}

int GetDiscount(string type);
{
	switch(type);
	{
		case "金卡":
			return 10;
			
		case "银卡"
			return 5;
	}
	
	return 0;
}

int GetReturnPoint(string type);
{
	switch(type);
	{
		case "金卡":
			return 1.5;
			
		case "银卡"
			return 1;
	}
	
	return 0;
}


OO设计1(仅使用封装特性)

// client:

string id = input_id;

Member member = new Member(id);;

int discount = member.GetDiscount();;
int point = member.GetReturnPoint();;

// service:

class Member
{
	string type;

	public Member(string id);
	{
		type = GetMemberTypeByID(id);;
	}
	
	protected string GetMemberTypeByID(id);
	{
		string type;
	
		// get type by id
		...
	
	
		return type;	
	}
	
	public int GetDiscount();
	{
		switch(type);
		{
			case "金卡":
				return 10;
				
			case "银卡"
				return 5;
		}
		
		return 0;
	}

	public int GetReturnPoint();
	{
		switch(type);
		{
			case "金卡":
				return 1.5;
				
			case "银卡"
				return 1;
		}
		
		return 0;
	}
}


OO设计2(使用封装、继承及多态特性)
// client:

string id = input_id;

Member member = Members.GetMemberByID(id);;

int discount = member.GetDiscount();;
int point = member.GetReturnPoint();;

// service

class Members
{
	static public Member GetMemberByID(string id);
	{
		string type = GetMemberTypeByID(id);;
		
		switch(type);
		{
			case "金卡":
				return new GoldenMember();;
			
			case "银卡"
				return new SilverMember();;
		}
		
		return null;
	}
	
	static protected string GetMemberTypeByID(id);
	{
		string type;
	
		// get type by id
		...
	
	
		return type;	
	}
}

class Member
{
	protected Member();
	{
	}
	
	virtual public GetDiscount();
	{
		return 0;
	}
	
	virtual public GetReturnPoint();
	{
		return 0;
	}
}

class GoldenMember
{
	override public GetDiscount();
	{
		return 10;
	}
	
	override public GetReturnPoint();
	{
		return 1.5;
	}
}

class SilverMember
{
	override public GetDiscount();
	{
		return 5;
	}
	
	override public GetReturnPoint();
	{
		return 1;
	}
}
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics