Adapter Pattern

Adapter Pattern

Definition-Converts the interface of a class into another interface clients expect. Lets classes work together that couldn’t otherwise because of incompatible interfaces.

How to use?

1.       The client makes a request to the adapter by calling a method on it using the target interface.

2.       The Adapter translates that request into one or more calls on the adaptee(target objects proceeding requests) using the Adaptee interface.

3.       The client receives the results of the call and never knows there is an adapter doing translation.

How to implement this approach (runtime behavior)?

 

Advantage: decouple the client from implemented interface, and if we expect the interface to change over time, the adapter encapsulates that change so that the client doesn’t have to be modified each time.

Example:Notebook and its ACPower Voltage

interface  power
{
    
public int getPower();
}

class  PowerAdapter  implements  power   //  like a transformer
{
    AcPower ac;
    
public PowerAdapter(AcPower ac)
    
{
        
this.ac = ac;
    }

    
public int getPower()
    
{
        
return ac.getACPowerVolt_110();
    }

}

class  PowerInChina  implements  power
{
    
public int getPower()
    
{
        
return 220;
    }

}

class  AcPower  {
    
public int getACPowerVolt_110()
    
{
        
return 110;
    }

}

class  NoteBook
{
    power P;
    String Name;
    
public NoteBook(String name)
    
{
        
this.Name = name;
    }

    
public void SetPower(power p)
    
{
        
this.P = p;
    }

    
public void DisplayVoltage()
    
{
        System.out.println(
"NoteBook:"+this.Name);
        System.out.println(
"Voltage needed is:"+P.getPower());
    }

}

 

// 结果
public   class  Main  {

    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
        AcPower powerInEurope = new AcPower();
        power powerInChina
=new PowerInChina();
        power powerAdapter
=new PowerAdapter(powerInEurope);
        
        NoteBook noteBook1
=new NoteBook("buy from China,now use in China");
        NoteBook noteBook2
=new NoteBook("buy from Europe,now use in China(");
        noteBook1.SetPower(powerInChina);
        noteBook2.SetPower(powerAdapter);
        
        noteBook1.DisplayVoltage();
        noteBook2.DisplayVoltage();
        
    }


}

 

//If u have anything interesting, pls contact with me. QQ:95491590

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值