static void Main(string[] args) { { Console.WriteLine("************************"); IHelper helper = new MySqlHelper(); helper.Query <Program>(); helper.Delete <Program>(); helper.Update <Program>(); helper.Add <Program>(); } { Console.WriteLine("************************"); IHelper helper = new OracleHelper(); helper.Query <Program>(); helper.Delete <Program>(); helper.Update <Program>(); helper.Add <Program>(); } { Console.WriteLine("************************"); IHelper helper = new SqlserverHelper(); helper.Query <Program>(); helper.Delete <Program>(); helper.Update <Program>(); helper.Add <Program>(); } { //引入第三方的redis,不适配 Console.WriteLine("************************"); IHelper helper = new RedisHelperInherit();//类适配器 helper.Query <Program>(); helper.Delete <Program>(); helper.Update <Program>(); helper.Add <Program>(); } {//组合优于继承 Console.WriteLine("***************"); Console.WriteLine("************************"); IHelper helper = new RedisHelperCombination();//对象适配器 helper.Query <Program>(); helper.Delete <Program>(); helper.Update <Program>(); helper.Add <Program>(); } //都做到了适配,都能新旧适配起来 //组合优于继承 1.继承是强侵入形的 会带过来父类的方法(有多余的东西) // 2.灵活性问题(组合是依赖抽象的,继承是依赖细节的) //应用总结: //属于不救模式,全新引入新的组件要用上的 //不能在项目一开始设计的时候就搞适配器,徒增难度 //时机选择 Console.WriteLine("Hello World!"); }
static void Main(string[] args) { try { { IHelper helper = new SqlServerHelper(); helper.Add <Program>(); helper.Delete <Program>(); helper.Query <Program>(); helper.Update <Program>(); } { IHelper helper = new OracleHelper(); helper.Add <Program>(); helper.Delete <Program>(); helper.Query <Program>(); helper.Update <Program>(); } { IHelper helper = new MysqlHelper(); helper.Add <Program>(); helper.Delete <Program>(); helper.Query <Program>(); helper.Update <Program>(); } { //由于Redis是第三方的类库,虽然当中也有增删改查, //但我们无法直接让其继承IHelper 故而无法像如下使用 //此时我们应当考虑适配器模式 // IHelper helper = new RedisHelper(); // helper.Add<Program>(); // helper.Delete<Program>(); // helper.Query<Program>(); // helper.Update<Program>(); } { IHelper helper = new RedisHelperInherit(); helper.Add <Program>(); helper.Delete <Program>(); helper.Query <Program>(); helper.Update <Program>(); RedisHelperInherit helperInherit = new RedisHelperInherit(); helperInherit.AddRedis <Program>(); //强侵入性,继承导致父类有的子类必须也有 } { IHelper helper = new RedisHelperCombination(); helper.Add <Program>(); helper.Delete <Program>(); helper.Query <Program>(); helper.Update <Program>(); } } catch (Exception e) { Console.WriteLine(e.Message); // throw; } }