zoukankan      html  css  js  c++  java
  • Adapter模式

    Adapter模式主要用于将一个类的接口转换为另外一个接口,通常情况下再不改变原有体系的条件下应对新的需求变化,通过引入新的适配器类来完成对既存体系的扩展和改造。实现方式主要包括:

    1.类的Adapter模式。

    通过引入新的类型来继承原有类型,同时实现新加入的接口方法。且缺点是耦合度高,需要引入过多的新类型。

    在这一新的设计体系中,两个新类型ChickenAdapter和EagleAdapter就是类的Adapter模式中新添加的类,他们分别继承自原有的类,从而保留原有类特性与行为,并实现添加ITweetable接口的新行为ToTweet().我们没有破坏原有Bird体系,同时添加了新的行为,

    2.对象的Adapter模式。

    通过聚合而非继承的方式来实现对原有系统的扩展,松散耦合,较少新的类型。

    具体的实现细节为:(这是在VS2010里根据设计好的类图自动在后台生成的代码,我们只要在方法里添加实现代码就ok了)

        public class BirdAdapter : ITweetable
        {
            private Bird _bird;
    
            public BirdAdapter(Bird bird)
            {
                _bird = bird;//throw new System.NotImplementedException();
            }
        
            public Bird Bird
            {
                get
                {
                    return _bird;//throw new System.NotImplementedException();
                }
                set
                {
                    _bird = value;
                }
            }
    
            public void ToTweet()
            {
                throw new NotImplementedException();
            }
    
            public void ShowType()
            {
                throw new System.NotImplementedException();
            }
    
            public void ShowColor()
            {
                throw new System.NotImplementedException();
            }
        }

      客户端调用为:

        class Program
        {
            static void Main(string[] args)
            {
                BirdAdapter ba = new BirdAdapter(new Chicken());
                ba.ShowColor();
                ba.ShowType();
            }
        }

    总结:类的Adapter模式以继承方式来实现,对象的Adapter模式则以聚合的方式来完成。根据面向对象多组合,少继承的原则,对象的Adapter模式更能体现松散耦合关系,应用更灵活

  • 相关阅读:
    canvas实现涂鸦板
    走进javascript——被忽视的DOM方法和属性
    走进javascript——DOM事件
    HTML5本地储存sessionStorage的销毁数据问题
    给微软的依赖注入框架写一些扩展方法
    一个支持 CodeFirst/DbFirst/ModelFirst 的数据库小工具
    用 C# 写一个 Redis 数据同步小工具
    SqlServer 利用游标批量更新数据
    WeihanLi.Npoi 根据模板导出Excel
    angular 构建可以动态挂载的配置服务
  • 原文地址:https://www.cnblogs.com/lxGIS/p/3333040.html
Copyright © 2011-2022 走看看