A interface defines a series functions func1 to func20. There are many derived classes which implements only parts of these 20 func. The implementation of func has its own pattern, for example: f1’s implementation has 2 kinds, f2’s implementation has 3 kinds. The derived class will implements about 3 to 5 number func defined in interface and all those implementations is chosen in defined kinds. Most of func in a derived class is empty means do nothing when outer model call it by refer a interface.
Is there a pattern to make fixed implementation to object and use them to config derived class? For example: Derived class D1 needs to implements f2 & f10, f2 use the first kind implementation which chosen from all 3 kinds. f10 use the second kind implementation which chosen from all 2 kinds.
My solution right now is simple: only derive from interface and override the functions it needs to, but the problem is: the increase of func implementation is much slower than derived class, because derived class construct by combination of different func. I have to hard copy code of func implementation code into derived class, that is not good. It is hard to maintain.
I want to make derived class configurable by primitive func codes, is it possible?
=====================================================================
I am clarify my problem and decorator indeed could solve this.
interface A {
f1();
f2();
...
f20();
}
f1-20 implementation is not arbitrary, they has fixed pattern. f1() has 3 kinds implementation, say, {1a},{1b},{1c}. f2() has 2 kinds: {2a},{2b}. Derived class which implements A only needs to override small number functions about 3-5. As you can see, the possible derived class definition(random chose some fn() to override and chose a kind of implementation from each fn()) is a combination, and number is huge. The consequence is fixed fn’s implementation will be copied every where.
Decorator solve this in manner of put every fn’s implementation such as {1a} into a decorator of interface A. So if we want a derived class only override f1 & f2 by {1a}{2b}, compose {1a}{2b} decorators to a object. The key is define a abstract class decorator base:
abstract class DecoratorBase : A {
A a;
DecoratorBase(A a){this.a=a;}
f1(){a.f1();}
f2(){a.f2();};
...
f20(){a.f20();};
}
And define some default process into base A (this can be omit if there is no default common process)
class BaseA {
f1(){} // no default code, do nothing
f5(){/*default code*/}
}
First kind implementation of f1():
class F1A : DecoratorBase {
F1A(A a){super(a);}
f1(){super.f1();/*1a*/}
}
Second kind implementation of f2():
class F2B : DecoratorBase {
F2B(A a){super(a);}
f2(){super.f2();/*2b*/}
}
Finally, combine them:
new F1A(new F2B(BaseA()));
Hmm, Decorator pattern seems appropriate?
http://en.wikipedia.org/wiki/Decorator_pattern
Possibly combined with Factory and/or Builder pattern.