Web Page Counter
Internet Date

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模式更能体现松散耦合关系,应用更灵活

posted @ 2013-09-22 14:28  LX一木  阅读(321)  评论(0编辑  收藏  举报