Analysis: Abstract Components--concrete components--Abstract decoration Class _ Concrete decoration class
Related UML Diagrams:
Class sum:
Related code:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacem_k3{classProgram {Static voidMain (string[] args) { Chari; Mobilephone Apple=NewApple (); 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=NewBluetooth (); Bluethooh. Decorate (apple); Bluethooh. SendMessage (); } if(i = ='2') {GPS GPS=NewGPS (); Gps. Decorate (apple); Gps. SendMessage (); } if(i = ='3') {Camera camera=NewCamera (); Camera. Decorate (apple); Camera. SendMessage (); } } } }}Abstract classmobilephone{ Publicmobilephone () {} Public Abstract voidSendMessage (); Public Abstract voidCall (); Public Abstract voidHello ();}classapple:mobilephone{ PublicApple ():Base(){ } Public Override voidSendMessage () {Console.WriteLine ("now,send Message ... Hello,i am Apple."); } Public Override voidCall () {Console.WriteLine ("now,calling ... Moxi moxi,i ' am Apple."); } Public Override voidHello () {Console.WriteLine ("Hello,there is Apple."); }}classmi:mobilephone{ PublicMi ():Base() { } Public Override voidSendMessage () {Console.WriteLine ("now,send Message ... Hello,i am Mi."); } Public Override voidCall () {Console.WriteLine ("now,calling ... Moxi moxi,i ' am Mi."); } Public Override voidHello () {Console.WriteLine ("Hello,there is Mi."); }}Abstract classadd:mobilephone{PrivateMobilephone _mobilephone; PublicADD ():Base() { } Public voiddecorate (mobilephone mobilephone) {_mobilephone=Mobilephone; } Public Override voidSendMessage () {_mobilephone. SendMessage (); } Public Override voidCall () {_mobilephone. Call (); } Public Override voidHello () {_mobilephone. Hello (); }}classbluetooth:add{ PublicBluetooth ():Base() { } Public Override voidSendMessage () {Base. Hello (); Connect (); } Public voidConnect () {Console.WriteLine ("initate Bluetooth of Phone,and connect ..."); }}classgps:add{ PublicGPS ():Base() { } Public Override voidSendMessage () {Base. Hello (); Location (); } Public voidLocation () {Console.WriteLine ("Now,open the GPS. Now,you is at ..."); }}classcamera:add{ PublicCamera ():Base() { } Public Override voidSendMessage () {Base. Hello (); Cansee (); } Public voidCansee () {Console.WriteLine ("Now,camera Open. Now,you can now open video calls ..."); }}
Operation Result:
Advantages:
1. Meet the OCP principle;
2. Can be arbitrarily combined, change the builder mode fixed combination situation, more flexibility.
M_k3 Decorator Mode