C#瞬态依赖模式

时间:2017-06-16 07:46:37

标签: c# dependencies

我有以下情况。 SomeClass依赖于IDiagram,而Diagram实现了该接口。 SomeClass的生命周期是应用程序的生命周期,但是图表的生命周期更短。假设按下某个按钮时它可能会改变。 由于我找不到任何令人满意的问题,我想出了下图所示的模式。

  • 图表的观察者会发现图表可以在更改时更改并设置正确的实例。
  • Observer将通过委派当前Diagram实例的方法来实现IDiagram接口。
  • SomeFactory会创建新的Diagrams和RaiseChanged。
  • SomeClass不会意识到这一点。

强制执行这种模式是个好主意,哪些缺点?这个问题有更好的解决方案吗?

enter image description here

使用IDependency而不是IDiagram的示例代码:

    private static void Main(string[] args)
    {
        var transientDependency = new TransientDependency();
        var dependencyObserver = new DependecyObserver(transientDependency);
        var dependencyFactory = new Factory(transientDependency);
        var someClass = new SomeClass(dependencyObserver);
        var someOtherClass = new SomeClass(dependencyObserver);

         // Note that someClass can only be used after the dependency has been created, because the Changed event has to be invoked
        dependencyFactory.CreateDependency();
    }

    public class DependecyObserver : IDependency
    {
        public DependecyObserver(TransientDependency transient)
        {
            transient.Changed += (s, dependency) => Dependency = dependency;
        }

        private Dependency Dependency { get; set; }

        public void SomeMethod()
        {
            Dependency.SomeMethod();
        }
    }

    public class Factory
    {
        private TransientDependency TransientDependency { get; }

        public Factory(TransientDependency transientDependency)
        {
            TransientDependency = transientDependency;
        }

        public void CreateDependency()
        {
            TransientDependency.RaiseChanged(new Dependency());
        }
    }

    public class SomeClass
    {
        public SomeClass(IDependency dependency)
        {
            dependency.SomeMethod();
        }
    }

    public class TransientDependency : TransientInstance<Dependency> { }

    public abstract class TransientInstance<T>
    {
        public EventHandler<T> Changed;

        public void RaiseChanged(T instance)
        {
            Changed?.Invoke(this, instance);
        }
    }

    public class Dependency : IDependency
    {
        public void SomeMethod()
        {
            throw new NotImplementedException();
        }
    }

    public interface IDependency
    {
        void SomeMethod();
    }

0 个答案:

没有答案