Design Patterns(Structural):Adapter in Java code

Structual Pattern: Adapter

 

什么是Adapter?

Convert the existing interfaces to a new interface to achieve compatibility and reusability of the unrelated classes in one application. Also known as Wrapper pattern.

 

 

Example:
To reuse classes and make new class compatible with existing ones. For example, A clean system is already designed, you want to add more job in, the Extra interface uses adapter pattern to plug in the existing system.

interface Clean {
    public void makeClean();
}
class Office implements Clean{
    public void makeClean() {
        System.out.println("Clean Office");
    }
}
class Workshop implements Clean{
    public void makeClean() {
        System.out.println("Clean Workshop");
    }
}

interface Extra extends Clean{
    public void takeCare();
}
class Facility implements Extra{
    public void makeClean() {
        System.out.println("Clean Facility");
    }
    public void takeCare() {
        System.out.println("Care has been taken");
    }
}

 

In order to reuse Workshop and Office classes,
we create an adapter interface Extra and add new job takeCare in the system.

class Test {
   static void Jobs (Extra job) {
       if (job instanceof Clean) 
           ((Clean)job).makeClean();
       if (job instanceof Extra)
           ((Extra)job).takeCare();
   }
   public static void main(String[] args) {
       Extra e = new Facility();
       Jobs(e);
       Clean c1 = new Office();
       Clean c2 = new Workshop();
       c1.makeClean();
       c2.makeClean();
       e.makeClean();
   }
}

 

 

原文:

http://www.javacamp.org/designPattern/

你可能感兴趣的:(java)