javadesign-patterns

what design pattern can I use to create an object that implements a specific interface or multiple or any combination among the available interfaces?


what design pattern can I use to create an object that implements a specific interface or multiple or any combination among the available interfaces? for Example say I have the following

interface A {
   void foo();
}

interface B {
   void bar();
}

interface C {
   void car();
}

class Agent {

}

I want to be able to say give me object of class Agent that implements interface A?

or

I want to be able to say give me object of class Agent that implements interfaces B?

or

I want to be able to say give me object of class Agent that implements interfaces C?

or

I want to be able to say give me object of class Agent that implements interfaces A,B?

or

I want to be able to say give me object of class Agent that implements interfaces B,C?

or

I want to be able to say give me object of class Agent that implements interfaces A,C?

or

I want to be able to say give me object of class Agent that implements interfaces A,B,C?

or

In general what I am looking for is to create an object which can have the functionality from any combination of interfaces.


Solution

  • Java is a statically typed language (see this question for details). This means that a variable you describe has a type which includes a set of interfaces that are implemented. So it does not make a lot of sense to say that you want an object of a certain class to vary the interfaces it implements.

    Having said that, I suspect you are trying to use interface for something for which it is not intended. For example if you want a class whose objects can have various capabilities that are determined when the object is created then there are design patterns that might work for you.

    Without knowing your needs it's hard to suggest specifics but here's a possible model:

    interface A {
        void foo();
    }
    
    interface B {
        void bar();
    }
    
    class Agent {
        private Optional<A> delegateA = Optional.empty();
        private Optional<B> delegateB = Optional.empty();
    
        public void addA(A delegate) {
            delegateA = Optional.of(delegate);
        }
    
        public boolean implementsA() {
            return delegateA.isPresent();
        }
    
        public void foo() {
            delegateA.ifPresent(A::foo);
        }
    }
    
    Agent agent = new Agent();
    agent.addA(() -> System.out.println("foo"));
    agent.implementsA();
    agent.foo();