What are the different methods for injecting cross-cutting concerns?

前端 未结 2 1547
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 01:01

What are the different methods for injecting cross-cutting concerns into a class so that I can minimize the coupling of the classes involved while keeping the code testable

2条回答
  •  醉话见心
    2020-12-08 01:44

    You can use the Observer pattern.

    The Subject holds a collection of Observers. When the Subject performs an action, it notifies the Observers of the change. The Observers can then perform an action without the Subject caring what that action is.

    Here's an example:

    public interface IThingObserver
    {
        void Notify();  // can also pass in a parameter with event information
    }
    
    public class Thing
    {
        private readonly ICollection observers;
    
        public Thing()
        {
            observers = new List();
        }
    
        public void RegisterObserver(IThingObserver observer)
        {
            observers.Add(observer);
        }
    
        public void UnregisterObserver(IThingObserver observer)
        {
            observers.Remove(observer);
        }
    
        private void NotifyObservers()
        {
            foreach (IThingObserver observer in observers)
            {
                observer.Notify();
            }
        }
    
        public void DoIt()
        {
            Console.WriteLine("Doing it...");
            NotifyObservers();
        }
    }
    
    public class LoggingThingObserver : IThingObserver
    {
        public void Notify()
        {
            Log.Write("It is done.");
        }
    }
    

    I'm used to Java, so please forgive any syntax errors.

提交回复
热议问题