设计模式05-SOLID(D)依赖倒置原则

Dependence Inversion Principle 依赖倒置原则

  • Dependency Inversion:依赖倒置。即面向抽象/接口编程。可参考依赖倒置原则。面向抽象编程,可大大提高灵活度,因为抽象可继承实现,而所有实现均可替代抽象。

  • 设计模式05-依赖倒置(依赖高层抽象,不应该依赖细节)
  • 以下例子是人物关系:人-关系-人 的读取。  以下例子中我们不应该在Program构造中直接读取底层细节,而是通过高层抽象依赖去完成操作(接口间的依赖,你只需要这个接口能干什么就行,怎么实现的你别管,大可不必在逻辑中对底层对象进行冗余操作
  • enum RelationShip
                {
                    Parent,
                    Child,
                    Silbing
                }
                class Person
                {
                    public string Name;
                    public DateTime DateOfBirth;
                }
                interface ISearchRelationShip
                {
                    IEnumerable<Person> SearchChild(string parentName); 
                }
    
                class RelationShips: ISearchRelationShip
                {
                    private List<(Person, RelationShip, Person)> ps = new List<(Person, RelationShip, Person)>();
                    public void AddRelationShip(Person parent, Person child) 
                    {
                        ps.Add((parent, RelationShip.Parent, child));
                        ps.Add((child, RelationShip.Child, parent)); 
                    }
    
                    public IEnumerable<Person> SearchChild(string parentName)
                    {
                        foreach (var item in ps)
                        {
                            if (item.Item1.Name==parentName&&item.Item2==RelationShip.Parent)
                            {
                                yield return item.Item3;
                            }
                        }
                    }
                }
    
                internal class Program
                {
                    public Program(ISearchRelationShip searchRelationShip)
                    {
                        Console.WriteLine("zhangsan has childs:");
                        foreach (var item in searchRelationShip.SearchChild("zhangsan"))
                        {
                            Console.WriteLine($"    -{item.Name}");
                        } 
                    }
                    static void Main(string[] args)
                    {
                        Person father = new Person() { Name="zhangsan"};
                        Person child1 = new Person() { Name = "zhangdada" };
                        Person child2 = new Person() { Name = "zhangxiaoxiao" };
                        RelationShips rs = new RelationShips();
                        rs.AddRelationShip(father, child1);
                        rs.AddRelationShip(father, child2);
                        new Program(rs);
    
                    }
                }

     

posted @ 2022-05-11 11:07  后跳  阅读(47)  评论(0)    收藏  举报