分离抽象和实现:
模拟场景—— 中杯,大杯,咖啡加奶,咖啡不加奶。其中,中杯和大杯为抽象,加奶和不加奶为行为:
class Program
{
public interface MakeCoffee
{
void Making();
}
///
/// 行为 - 牛奶咖啡(加奶)
///
public class WhiteCoffee : MakeCoffee
{
public void Making()
{
Console.WriteLine("牛奶咖啡");
}
}
///
/// 行为 - 原味咖啡(不加奶)
///
public class BlackCoffee : MakeCoffee
{
public void Making()
{
Console.WriteLine("原味咖啡");
}
}
///
/// 单件模式类用来加载当前MakeCoffee
///
public sealed class MakeCoffeeSingleton
{
private static MakeCoffee _instance;
public MakeCoffeeSingleton(MakeCoffee instance)
{
_instance = instance;
}
public MakeCoffee Instance()
{
return _instance;
}
}
///
/// 基类
///
public abstract class CupCoffee
{
private MakeCoffee _makeCoffee;
public CupCoffee(MakeCoffeeSingleton instance)
{
_makeCoffee = instance.Instance();
}
public MakeCoffee MakeCoffee
{
get { return _makeCoffee; }
}
public abstract void Make();
}
///
/// 抽象 - 中杯
///
public class MediumCoffee : CupCoffee
{
public MediumCoffee(MakeCoffeeSingleton makecoffee)
: base(makecoffee)
{
}
public override void Make()
{
Console.Write("中杯");
this.MakeCoffee.Making();
}
}
///
/// 抽象 - 大杯
///
public class LargeCoffee : CupCoffee
{
public LargeCoffee(MakeCoffeeSingleton makecoffee)
: base(makecoffee)
{
}
public override void Make()
{
Console.Write("中杯");
this.MakeCoffee.Making();
}
}
static void Main(string[] args)
{
MakeCoffeeSingleton whiteCoffeeSingleton = new MakeCoffeeSingleton(new WhiteCoffee());
// 中杯牛奶咖啡
MediumCoffee mediumWhiteCoffee = new MediumCoffee(whiteCoffeeSingleton);
mediumWhiteCoffee.Make();
// 大杯牛奶咖啡
LargeCoffee largeCupWhiteCoffee = new LargeCoffee(whiteCoffeeSingleton);
largeCupWhiteCoffee.Make();
MakeCoffeeSingleton blackCoffeeSingleton = new MakeCoffeeSingleton(new BlackCoffee());
// 中杯原味咖啡
MediumCoffee mediumBlackCoffee = new MediumCoffee(blackCoffeeSingleton);
mediumBlackCoffee.Make();
// 大杯牛奶咖啡
LargeCoffee largeCupBlackCoffee = new LargeCoffee(blackCoffeeSingleton);
largeCupBlackCoffee.Make();
Console.ReadKey();
}
}