CSharp: Proxy Pattern in donet core 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | /// <summary> /// Abstract class Subject /// 代理模式 Proxy Pattern /// Structural Design Patterns /// geovindu, Geovin Du edit /// </summary> public abstract class Subject { public abstract void DoSomeWork(); } /// <summary> /// ConcreteSubject class /// </summary> public class ConcreteSubject : Subject { public override void DoSomeWork() { Console.WriteLine( "I've processed your request.\n" ); } } /// <summary> /// Proxy class /// </summary> public class Proxy : Subject { Subject subject; string [] registeredUsers; string currentUser; /// <summary> /// /// </summary> /// <param name="currentUser"></param> public Proxy( string currentUser) { /* * Avoiding to instantiate ConcreteSubject * inside the Proxy class constructor. */ //subject = new ConcreteSubject(); //Registered users registeredUsers = new string [] { "Admin" , "Rohit" , "Sam" }; this .currentUser = currentUser; } /// <summary> /// /// </summary> public override void DoSomeWork() { Console.WriteLine($ "{currentUser} wants to access into the system." ); if (registeredUsers.Contains(currentUser)) { Console.WriteLine($ "Welcome, {currentUser}." ); //Lazy initialization: We'll not instantiate until the method is called through an authorized user. if (subject == null ) { subject = new ConcreteSubject(); } subject.DoSomeWork(); } else { Console.WriteLine($ "Sorry {currentUser}, you do not have access into the system." ); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | /// <summary> /// 代理模式 Proxy Pattern /// Structural Design Patterns /// geovindu, Geovin Du edit /// </summary> public interface IBankAccount { void Deposit( int amount); bool Withdraw( int amount); string ToString(); } /// <summary> /// /// </summary> public class BankAccount : IBankAccount { private int balance; private int overdraftLimit = -500; /// <summary> /// /// </summary> /// <param name="amount"></param> public void Deposit( int amount) { balance += amount; WriteLine($ "Deposited ${amount}, balance is now {balance}" ); } /// <summary> /// /// </summary> /// <param name="amount"></param> /// <returns></returns> public bool Withdraw( int amount) { if (balance - amount >= overdraftLimit) { balance -= amount; WriteLine($ "Withdrew ${amount}, balance is now {balance}" ); return true ; } return false ; } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return $ "{nameof(balance)}: {balance}" ; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> public class Log<T> : DynamicObject where T : class , new () { private readonly T subject; private Dictionary< string , int > methodCallCount = new Dictionary< string , int >(); /// <summary> /// /// </summary> /// <param name="subject"></param> /// <exception cref="ArgumentNullException"></exception> protected Log(T subject) { this .subject = subject ?? throw new ArgumentNullException(paramName: nameof(subject)); } /// <summary> /// factory method /// </summary> /// <typeparam name="I"></typeparam> /// <param name="subject"></param> /// <returns></returns> /// <exception cref="ArgumentException"></exception> public static I As<I>(T subject) where I : class { if (! typeof (I).IsInterface) throw new ArgumentException( "I must be an interface type" ); // duck typing here! return new Log<T>(subject).ActLike<I>(); } /// <summary> /// /// </summary> /// <typeparam name="I"></typeparam> /// <returns></returns> /// <exception cref="ArgumentException"></exception> public static I As<I>() where I : class { if (! typeof (I).IsInterface) throw new ArgumentException( "I must be an interface type" ); // duck typing here! return new Log<T>( new T()).ActLike<I>(); } /// <summary> /// /// </summary> /// <param name="binder"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object [] args, out object result) { try { // logging WriteLine($ "Invoking {subject.GetType().Name}.{binder.Name} with arguments [{string.Join(" , ", args)}]" ); // more logging if (methodCallCount.ContainsKey(binder.Name)) methodCallCount[binder.Name]++; else methodCallCount.Add(binder.Name, 1); result = subject ?.GetType() ?.GetMethod(binder.Name) ?.Invoke(subject, args); return true ; } catch { result = null ; return false ; } } /// <summary> /// /// </summary> public string Info { get { var sb = new StringBuilder(); foreach ( var kv in methodCallCount) sb.AppendLine($ "{kv.Key} called {kv.Value} time(s)" ); return sb.ToString(); } } // will not be proxied automatically public override string ToString() { return $ "{Info}{subject}" ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | /// <summary> /// 代理模式 Proxy Pattern /// Structural Design Patterns /// geovindu, Geovin Du edit /// </summary> public enum Op : byte { [Description( "*" )] Mul = 0, [Description( "/" )] Div = 1, [Description( "+" )] Add = 2, [Description( "-" )] Sub = 3 } /// <summary> /// /// </summary> public static class OpImpl { /// <summary> /// /// </summary> static OpImpl() { var type = typeof (Op); foreach (Op op in Enum.GetValues(type)) { MemberInfo[] memInfo = type.GetMember(op.ToString()); if (memInfo.Length > 0) { var attrs = memInfo[0].GetCustomAttributes( typeof (DescriptionAttribute), false ); if (attrs.Length > 0) { opNames[op] = ((DescriptionAttribute)attrs[0]).Description[0]; } } } } /// <summary> /// /// </summary> private static readonly Dictionary<Op, char > opNames = new Dictionary<Op, char >(); /// <summary> /// notice the data types! /// </summary> private static readonly Dictionary<Op, Func< double , double , double >> opImpl = new Dictionary<Op, Func< double , double , double >>() { [Op.Mul] = ((x, y) => x * y), [Op.Div] = ((x, y) => x / y), [Op.Add] = ((x, y) => x + y), [Op.Sub] = ((x, y) => x - y), }; /// <summary> /// /// </summary> /// <param name="op"></param> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public static double Call( this Op op, int x, int y) { return opImpl[op](x, y); } /// <summary> /// /// </summary> /// <param name="op"></param> /// <returns></returns> public static char Name( this Op op) { return opNames[op]; } } /// <summary> /// /// </summary> public class Problem { private readonly List< int > numbers; private readonly List<Op> ops; /// <summary> /// /// </summary> /// <param name="numbers"></param> /// <param name="ops"></param> public Problem(IEnumerable< int > numbers, IEnumerable<Op> ops) { this .numbers = new List< int >(numbers); this .ops = new List<Op>(ops); } /// <summary> /// /// </summary> /// <returns></returns> public int Eval() { var opGroups = new [] { new [] {Op.Mul, Op.Div}, new [] {Op.Add, Op.Sub} }; startAgain: foreach ( var group in opGroups) { for ( var idx = 0; idx < ops.Count; ++idx) { if ( group .Contains(ops[idx])) { // evaluate value var op = ops[idx]; var result = op.Call(numbers[idx], numbers[idx + 1]); // assume all fractional results are wrong if (result != ( int )result) return int .MinValue; // calculation won't work numbers[idx] = ( int )result; numbers.RemoveAt(idx + 1); ops.RemoveAt(idx); if (numbers.Count == 1) return numbers[0]; goto startAgain; // :) } } } return numbers[0]; } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { var sb = new StringBuilder(); int i = 0; for (; i < ops.Count; ++i) { sb.Append(numbers[i]); sb.Append(ops[i].Name()); } sb.Append(numbers[i]); return sb.ToString(); } } /// <summary> /// /// </summary> public class TwoBitSet { // 64 bits --> 32 values private readonly ulong data; /// <summary> /// /// </summary> /// <param name="data"></param> public TwoBitSet( ulong data) { this .data = data; } /// <summary> /// /// </summary> /// <param name="index"></param> /// <returns></returns> public byte this [ int index] { get { var shift = index << 1; ulong mask = (0b11U << shift); return ( byte )((data & mask) >> shift); } } } |
调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | /// <summary> /// Client class /// 代理模式 Proxy Pattern /// Structural Design Patterns /// geovindu, Geovin Du edit /// </summary> class Client { static void Main( string [] args) { Console.WriteLine( "***Proxy Pattern Demo2.***\n" ); //Authorized user-Admin Subject proxy = new Proxy( "Admin" ); proxy.DoSomeWork(); //Authorized user-Sam proxy = new Proxy( "Sam" ); proxy.DoSomeWork(); //Unauthorized User-Robin proxy = new Proxy( "Robin" ); proxy.DoSomeWork(); // var numbers = new [] { 1, 3, 5, 7 }; int numberOfOps = numbers.Length - 1; for ( int result = 0; result <= 10; ++result) { for ( var key = 0UL; key < (1UL << 2 * numberOfOps); ++key) { var tbs = new TwoBitSet(key); var ops = Enumerable.Range(0, numberOfOps) .Select(i => tbs[i]).Cast<Op>().ToArray(); var problem = new Problem(numbers, ops); if (problem.Eval() == result) { Console.WriteLine($ "{new Problem(numbers, ops)} = {result}" ); break ; } } } // //var ba = new BankAccount(); var ba = Log<BankAccount>.As<IBankAccount>(); ba.Deposit(100); ba.Withdraw(50); WriteLine(ba); Console.ReadKey(); } } |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | **Proxy Pattern Demo2.*** Admin wants to access into the system. Welcome, Admin. I've processed your request. Sam wants to access into the system. Welcome, Sam. I've processed your request. Robin wants to access into the system. Sorry Robin, you do not have access into the system. 1-3-5+7 = 0 1*3+5-7 = 1 1+3+5-7 = 2 1*3-5+7 = 5 1+3-5+7 = 6 1*3*5-7 = 8 1+3*5-7 = 9 1-3+5+7 = 10 Invoking BankAccount.Deposit with arguments [100] Deposited $100, balance is now 100 Invoking BankAccount.Withdraw with arguments [50] Withdrew $50, balance is now 50 Deposit called 1 time(s) Withdraw called 1 time(s) balance: 50 |
https://github.com/apress/pro-c-sharp-10
https://github.com/ProfessionalCSharp/ProfessionalCSharp2021
https://github.com/lianggan13/CSharp-in-a-Nutshell
https://github.com/markjprice/cs10dotnet6
https://github.com/PacktPublishing/.NET-Design-Patterns
https://sourceforge.net/projects/design-patterns-library.mirror/files/ NET6 NET5 Design Patterns
https://kafle.io/tutorials/asp-dot-net/Repository-Pattern-and-Unit-of-Work
https://github.com/BartVandewoestyne/Design-Patterns-GoF C++
https://www.codeproject.com/Articles/667197/Design-Patterns
https://www.dofactory.com/net/design-patterns
https://www.go4expert.com/articles/design-patterns-simple-examples-t5127/
https://www.wiley.com/en-us/Professional+ASP+NET+Design+Patterns-p-9780470292785#downloads-section
https://github.com/mono0926/Professional-ASP.NET-Design-Patterns
https://resources.oreilly.com/examples/9780596527730/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!