简体   繁体   中英

Java- Adapter design pattern implmentation variations

I'm new to design pattern subject area and keen to understand the implementation variations of design patterns. I have seen the following structure for adapter class in adapter design pattern in numerous tutorials on web. (Following code sample is extracted from wikipedia )

public class ClassAFormat1 implements StringProvider {
    private ClassA classA = null;

    public ClassAFormat1(final ClassA A) {
        classA = A;
    }

    public String getStringData() {
        return format(classA.toString());
    }
}

If i'm not mistaken, ClassA is the adaptee and StringProvider is the target in this example (Classes are not provided here).

I have made a small adjustment to the above code by defining and initializing the adaptee class within the method of target. I know its strange but want to know whether it still belongs to the adapter design pattern.

public class ClassAFormat1 implements StringProvider {



    public String getStringData() {

               ClassA classA = new ClassA();
        return format(classA.toString());
    }
}

Has the above adapter class written according to the guidelines of adapter design pattern?

Thank you.

The purpose of adapters, is to have the ability to treat objects as if they are instances of other classes.
In the example you provided, and instance of ClassA can be "treated" as StringProvider simply by using new ClassAFormat1(a) where a 's type is ClassA .

With the change you added, you can't take different instances of ClassA and make them behave as StringProvider . In this case ClassAFormat1 cannot be use as an adapter from ClassA to StringProvider (in the sence that you cannot give it any instance of ClassA and make it behaves like a StringProvider .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM