标签:
分析:抽象组件——具体组件——抽象装饰类_具体装饰类
相关UML图:
类总括:
相关代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace M_K3 { class Program { static void Main(string[] args) { char i; MobilePhone apple = new Apple(); apple.SendMessage(); apple.Call(); Console.WriteLine("--------------------------------------"); Console.WriteLine(" Please select new function."); Console.WriteLine(" Bluetooth----1."); Console.WriteLine(" GPS----2."); Console.WriteLine(" Camera----3."); Console.WriteLine(" End----0."); Console.WriteLine("---------------------------"); Console.WriteLine("Input the choice:"); while (true) {i = (char)Console.Read(); if (i == ‘0‘) { break; } if (i == ‘1‘) { Bluetooth bluethooh = new Bluetooth(); bluethooh.Decorate(apple); bluethooh.SendMessage(); } if (i == ‘2‘) { GPS gps = new GPS(); gps.Decorate(apple); gps.SendMessage(); } if (i == ‘3‘) { Camera camera = new Camera(); camera.Decorate(apple); camera.SendMessage(); } } } } } abstract class MobilePhone { public MobilePhone() { } public abstract void SendMessage(); public abstract void Call(); public abstract void Hello(); } class Apple : MobilePhone { public Apple() : base(){ } public override void SendMessage() { Console.WriteLine("Now,send message...Hello,I am Apple."); } public override void Call() { Console.WriteLine("Now,calling...Moxi Moxi,I‘am Apple."); } public override void Hello() { Console.WriteLine("Hello,there is Apple."); } } class Mi : MobilePhone { public Mi() : base() { } public override void SendMessage() { Console.WriteLine("Now,send message...Hello,I am Mi."); } public override void Call() { Console.WriteLine("Now,calling...Moxi Moxi,I‘am Mi."); } public override void Hello() { Console.WriteLine("Hello,there is Mi."); } } abstract class Add : MobilePhone { private MobilePhone _mobilephone; public Add() : base() { } public void Decorate(MobilePhone mobilephone) { _mobilephone = mobilephone; } public override void SendMessage() { _mobilephone.SendMessage(); } public override void Call() { _mobilephone.Call(); } public override void Hello() { _mobilephone.Hello(); } } class Bluetooth : Add { public Bluetooth() : base() { } public override void SendMessage() { base.Hello(); Connect(); } public void Connect() { Console.WriteLine("Initate Bluetooth of phone,and connect..."); } } class GPS : Add { public GPS() : base() { } public override void SendMessage() { base.Hello(); Location(); } public void Location() { Console.WriteLine("Now,open the GPS.Now,you are at..."); } } class Camera : Add { public Camera() : base() { } public override void SendMessage() { base.Hello(); Cansee(); } public void Cansee() { Console.WriteLine("Now,Camera open.Now,You can now open video calls..."); } }
运行结果:
优点:
1. 满足OCP原则;
2.可随意组合,改变建造者模式固定组合的情况,更具灵活性。
标签:
原文地址:http://www.cnblogs.com/Elix-kakulo/p/5070673.html