简体   繁体   English

Java-Adapter设计模式实现的变体

[英]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 ) (以下代码示例摘自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). 如果我没记错的话,在此示例中,ClassA是适配器,StringProvider是目标(此处未提供类)。

I have made a small adjustment to the above code by defining and initializing the adaptee class within the method of target. 通过在目标方法内定义和初始化Adaptee类,对上述代码进行了一些小的调整。 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 . 在这个例子中你提供,并实例ClassA可以被“处理”为StringProvider简单地通过使用new ClassAFormat1(a) ,其中a的类型是ClassA

With the change you added, you can't take different instances of ClassA and make them behave as StringProvider . 添加更改后,您将无法采用ClassA不同实例,并使它们表现为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 . 在这种情况下, ClassAFormat1不能用作从ClassAStringProvider的适配器(因为您不能为它提供ClassA任何实例,并且使其行为类似于StringProvider

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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