Adapter Pattern

Convert interface of a class into another interface clients expect.
Adapter lets classes work together that are not otherwise because of incompatible interfaces.
-- Design Patterns
1.Adapter 1: By constructor.

// interface 1
public interface IPeg(){
    pubic void insertHole();
}

// interface 2
public interface IRoundPeg(){
    public void insertRoundHole();
}

// impl of interface 1 of IPeg.
public class IPegImpl implements IPeg {
    public void insertHole(){
        System.out.println("Insert hole.");
    }
}

//impl of interface 2.
public class IRoundPegImpl implements IRoundPeg {
    public void insertRoundPeg(){
        System.out.println("Insert into round hole.");
    }
}

//Adapter: Now we want to use interface 1 of IPeg only. We get an adapter.
public class AdapterMode1 implements IPeg {
    private IRoundPeg iRoundPeg;
    public AdapterPeg(IRoundPeg iRoundPeg){    // Pay more attention here. By constructor. 
        this.iRoundPeg = iRoundPeg; 
    }
    
    public void insertHole(){
        iRoundPeg.insertRoundHole();    // Now we get the function of interface 2.
    }
}

//main: to test adapter
public class AdapterTest {
    public static void main(){
        // Pay more attention here. arg of new IRoundPegImpl().
        // IPeg iPeg = new IPegImpl();   // for function 1.
        IPeg ipeg = new AdapterMode1(new IRoundPegImpl());   //  **
        iPeg.insertHole();    // output: Insert into round hole.
    }
}

2.Adapter 2: class adapter.
extends IRoundPegImpl + implements IPeg.

public class AdapterMode2 extends IRoundPegImpl implements IPeg {
    public void insertHole(){
        super.insertRoundHole();
    }
}
// test way is the same as above.

3.Adapter 3: Two-way adapter.
implements IPeg + implements IRoundPeg. By constructor.

public class AdapterMode3 implements IPeg, IRoundPeg {
    private IPeg iPeg;
    private IRoundPeg iRoundPeg;

    public AdapterMode3(IPeg iPeg){
        this.iPeg = iPeg;
    }
    public AdapterMode3(IRoundPeg iRoundPeg){
        this.iRoundPeg = iRoundpeg;
    }

    @Override
    public void insertHole(){    // method of interface 1: IPeg
        iRoundPeg.insertRoundHole();
    }

    @Override
    public void insertRoundhole(){    // method of interface 2: IRoundPeg
        iPeg.insertHole();
    }
}

// main: test two-way adapter
public class AdapterTest {
    public static void main(String[] args){
        AdapterMode3 adapter1 = new AdapterMode3(new IPegImpl());
        AdpaterMode3 adapter2 = new AdapterMode3(new IRoundpegImpl());

        adapter1.insertHole();    // output: Insert into round hole.
        adapter2.insertRoundHole();    //  output: Insertr into hole.
    }
}

你可能感兴趣的:(Adapter Pattern)