6

I am trying to implement the following pattern in a Cache layer.

I'm splitting the implementation of possible Cache methods such as getUsers() in UserCache Class, getLikes() in PostsCache class.

But I'd like all these methods to be accessible from a Single class object such as Cache.getUsers() , Cache.getLikes()

The reason behind this is, I'd like the developers who're using this layer to be unaware of the split that's been done behind this layer.

I've done the following

2 Interfaces - UserCache, PostsCache and 2 Classes implementing the interfaces - UserCacheImpl, PostsCacheImpl.

I tried to introduce a abstract class AbstractCache that implements these 2 interfaces and then this Cache class will extend that abstract class. But that failed :(

Now how can I combine these two be accessible from a single Cache object. Please guide me

  • 1
    what programming language do you use? neither question text nor tags help find it out – gnat Jul 8 '17 at 16:51
  • @gnat I've added the missed detail. It's java – Magesh Kumaar Jul 8 '17 at 17:05
  • 2
    This is called a Facade by the way. It harkens back to the dark ol' days of COM when you really really really never wanted to change a public interface. Today it's mostly seen in anti-corruption layers. en.wikipedia.org/wiki/Facade_pattern – RubberDuck Jul 9 '17 at 20:09
13

It's perfectly possible for you to have

a[n] abstract class AbstractCache that implements these 2 interfaces and then this Cache class will extend that abstract class

public interface UserCache {
    int getUsers();
}

public interface PostsCache {
    int getLikes();
}

public abstract class AbstractCache implements UserCache, PostsCache {
    @Override public int getUsers() { return 12; }
    @Override public int getLikes() { return 34; }
}

public class Cache extends AbstractCache {
}

and that all compiles perfectly fine. What it is of course not possible to do in Java is to have multiple inheritance, where one class extends two classes (as opposed to implementing two interfaces), so you can't do

public abstract class AbstractCache extends UserCacheImpl, PostsCacheImpl {
}

and I suspect this is what you're actually trying to do. The solution here is to favour composition over inheritance:

public abstract class AbstractCache implements UserCache, PostsCache {
    private UserCacheImpl userCache;
    private PostsCacheImpl postsCache;

    public AbstractCache() {
        userCache = new UserCacheImpl();
        postsCache = new PostsCacheImpl();
    }

    @Override public int getUsers() { return userCache.getUsers(); }
    @Override public int getLikes() { return postsCache.getLikes(); }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.