java-pattern 之 读书笔记6 ---Adapter

Adapter is one of the structural Patterns。
从今天开始,研究的是结构模式(Structural Patterns),首先从Adapter模式开始。
Adapter模式又称适配器模式。它是用来将一种接口转换成客户所需要的另一种接口,从而使原本因接口不同而无法一起工作的两个类能够一起工作。

例如:翻译机,将中文翻译成英文,这样中国人用这套设备说给英国人听的时候,英国人接受到的将会是英文,这个过程就是adapter的过程。

首先中国人说中文:
    /// <summary>
    
/// ChinesePeople 中国人说中文。
    
/// </summary>

    public class ChinesePeople
    
{
        
public ChinesePeople()
        
{
        }


        
public virtual string sayChinese()
        
{
            
return "你好";
        }

    }

英国人说英文(能听懂的是英文):
    /// <summary>
    
/// EnglishMan 英国人。
    
/// </summary>

    public class EnglishMan
    
{
        
public EnglishMan()
        
{
        }


        
public string sayEnglish()
        
{
            
return "hello";
        }

    }
中国人向英国人讲话(配备适配器):
    /// <summary>
    
/// Adapter 将中文译成英文(调用Adapter.sayChinese()得到sayEnglish())。
    
/// </summary>

    public class Adapter : ChinesePeople
    
{
        
public Adapter()
        
{}
    
        
private EnglishMan _enlishman = new EnglishMan();

        
public override string sayChinese()
        
{
            
return _enlishman.sayEnglish();
        }

    }

那么讲话的结果就是英国人能听懂的“hello”了。
适配器就起这种使不同的接口能统一工作的作用。

posted on 2005-08-01 16:27  Michael J  阅读(326)  评论(0)    收藏  举报