/// <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."); } } }
/// <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}"; } }
/// <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); } } }
调用:
/// <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(); } }
输出:
**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/