《HeadFirst设计模式》读书摘记(7)--适配器模式

适配器模式定义:将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。
        这个模式可以通过创建适配器进行接口转换,让不兼容的就口变得兼容。可以让客户从实现的接口解耦。           
代码如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace 设计模式
{
    
//测试代码
    class Program
    
{
        
static void Main(string[] args)
        
{
            MallardDuck duck 
= new MallardDuck();

            WildTurkey turkey 
= new WildTurkey();
            Duck trukeyAdapter 
= new TurkeyAdapter(turkey);

            Console.WriteLine(
"The Turkey says");
            turkey.Gobble();
            turkey.Fly();

            Console.WriteLine(
"\n The Duck says.");
            Test(duck);

            Console.WriteLine(
"\n The TurkeyAdapter says..");
            Test(trukeyAdapter);

            Console.ReadLine();


        }

        
static void Test(Duck duck)
        
{
            duck.Quanck();
            duck.Fly();
        }

    }

    
//目标接口
    public interface Duck
    
{
        
void Quanck();
        
void Fly();
    }

    
    
public class MallardDuck : Duck
    
{
        
public void Quanck()
        
{
            System.Console.WriteLine(
"Quack");
        }

        
public void Fly()
        
{
            Console.WriteLine(
"I'm flying");
        }

    }

    
//被适配接口
    public interface Turkey
    
{
        
void Gobble();
        
void Fly();
    }

    
//被适配者
    public class WildTurkey : Turkey
    
{
        
public void Gobble()
        
{
            Console.WriteLine(
"Gobble gobble");
        }

        
public void Fly()
        
{
            Console.WriteLine(
"I'm flying a short distance");
        }

    }

    
//适配器,将被适配者(火鸡)适配成目标接口(鸭子)
    public class TurkeyAdapter : Duck
    
{
        Turkey turkey;

        
public TurkeyAdapter(Turkey turkey)
        
{
            
this.turkey = turkey;
        }


        
public void Quanck()
        
{
            turkey.Gobble();
        }

        
public void Fly()
        
{
            
for (int i = 0; i < 5; i++)
            
{
                turkey.Fly();
            }

        }

    }

}

posted @ 2008-03-15 16:35  collum  阅读(121)  评论(0)    收藏  举报