本质:分离构建算法和部件构造
场景:模拟学分评级系统,评分为:必修课,选修课,实践课,最终评分为所有课程均分;
class Program
{
///
/// 课程类
///
public class Course
{
private IDictionary _courses = new Dictionary();
public IDictionary Courses
{
get { return _courses; }
}
public void Select(string courseName, decimal score)
{
_courses.Add(courseName, score);
}
public int CourseCount()
{
return _courses.Count;
}
}
///
/// 接口 - 定义过程
///
public interface Builder
{
void GetRequiredScore(); //必修课成绩
void GetEletiveScore(); //选修课成绩
void GetPracticeScore(); //实践课成绩
decimal GetAveScore(); //获取总成绩
}
///
/// 本科生
///
public class UndergraduateBuilder : Builder
{
private Course _courses = new Course();
public void GetRequiredScore()
{
_courses.Select("语文", 85);
_courses.Select("数学", 95);
_courses.Select("英语", 90);
}
public void GetEletiveScore()
{
_courses.Select("物理", 87);
_courses.Select("化学", 80);
}
public void GetPracticeScore()
{
_courses.Select("体育", 95);
}
public decimal GetAveScore()
{
decimal sum = 0;
foreach (KeyValuePair kvp in _courses.Courses)
{
Console.WriteLine(kvp.Key + " " + kvp.Value);
sum += kvp.Value;
}
return sum / _courses.CourseCount();
}
}
///
/// 研究生
///
public class GraduateBuilder : Builder
{
private Course _courses = new Course();
public void GetRequiredScore()
{
_courses.Select("高等数学", 75);
_courses.Select("英语六级", 350);
}
public void GetEletiveScore()
{
_courses.Select("操作系统", 87);
}
public void GetPracticeScore()
{
_courses.Select("体育", 80);
}
public decimal GetAveScore()
{
decimal sum = 0;
foreach (KeyValuePair kvp in _courses.Courses)
{
Console.WriteLine(kvp.Key + " " + kvp.Value);
sum += kvp.Value;
}
return sum / _courses.CourseCount();
}
}
public static class ScoreManager
{
public static decimal GetAllScore(Builder builder)
{
builder.GetRequiredScore();
builder.GetEletiveScore();
builder.GetPracticeScore();
return builder.GetAveScore();
}
}
static void Main(string[] args)
{
decimal score = ScoreManager.GetAllScore(new UndergraduateBuilder());
Console.WriteLine("总评:" + score);
Console.ReadKey();
}
}