简体   繁体   中英

Design Pattern : Applying behavior on objects of different family

I have a set of classes from third party library which I don't have access to the source. I need to add some common behavior on these objects by using a design pattern. How do I apply Decorator or Visitor pattern to these objects?

These objects have no common base class. These are either plain objects or having uncommon interfaces. I cannot add a common interface to these classes because these classes are not part of my project.

How do I add common behavior to these classes without checking 'instance of' in a single method.

To work with Decorator you need some well defined interface . So the first task is to find an interface. As third party classes dont have an interface, Adapter pattern comes to rescue. You can define your own interface and adapt the third party classes to interfaces you require them to adhere to.

class YourTypeAdapter implements YourAdapterInterface{
    private Type instance; //need to adapt this as no interface present

    public void interfaceMethod(){
        instance.someTypeSpecificMethod();
        //perform extra steps here 
    }
}

在此处输入图片说明

In this way you can adapt those Types which do not have a common interface into a suitable interface hierarchy for you. You can also add additional functionality that you want to add to this adapter. Or you can go ahead and use a decorator to YourTypeAdapter as now you have an interface YourAdapterInterface to work with.

References: - OODesign Adapter pattern

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