When we cannot or do not need direct access to a role for some reason, we can implement our specific behavior through proxy objects, which are similar to the role of matchmaker.
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;namespaceconsoleapplication1{classProgram {/// <summary> ///Abstract Roles/// </summary> Public Abstract classRole { Public Abstract voidbuyproduct (); } /// <summary> ///Real characters/// </summary> Public classRealbuyrole:role { Public Override voidbuyproduct () {Console.WriteLine ("buy Something"); } } /// <summary> ///Agent Role/// </summary> Public classProxy:role {PrivateRealbuyrole Realrole; Public Override voidbuyproduct () {if(Realrole = =NULL) {Realrole=NewRealbuyrole (); } This. Prebuyproduct (); //invoke the Real role methodrealrole.buyproduct (); This. Postbuyproduct (); } /// <summary> ///the predecessor behavior of the agent role/// </summary> Public voidprebuyproduct () {Console.WriteLine ("things to do before you buy something"); } /// <summary> ///Post behavior of the agent role/// </summary> Public voidpostbuyproduct () {Console.WriteLine ("things to do after you buy something"); } } Static voidMain (string[] args) {Role Proxy=NewProxy (); Proxy. Buyproduct (); } }}
Proxy Mode C #