I am working on an Android project and i am facing this situation.
I have 2 class :
class A extends B
{
openDoor(){
//impl
}
closeDoor(){
//impl
}
}
class X extends Y{
openDoor(){
//impl
}
closeDoor(){
//impl
}
}
Now if you observe the are two methods common in both the classes openDoor()
and closeDoor()
what is the best way to avoid duplicate methods?
My Approach
class ContainingDuplicateMethods{
openDoor(){
//impl
}
closeDoor(){
//impl
}
}
}
Create a object of ContainingDuplicateMethods in both the class and call the methods, which we call it as Strategy Pattern,but is this the best solution? why because in large projects we cannot follow this approach and people say it not GOOD PRACTICE, in that case what approach do i need to follow ?
Please note that class A and X
are already extending other classes and also i dont want to use static because - Static members are loaded into memory when the program execution starts and will be in memory until the program is terminated, say my code runs continuously for days or weeks and keeps on creating many number of objects using the static references so there might be a chance that we could run out of memory.
"Favour composition over inheritance" is a useful thing to remember.
Have a Door
class with open and close. Include a Door
as a member of both A
and B
.
Voila, job done.
So A.getDoor().close()
. B.getDoor().open()
etc.
If you need a common interface for both A
and B
(so you can use either somewhere) then create
interface HasDoor {
Door getDoor();
}
Now A
and B
can extend any class you like and implement HasDoor
. Any class requiring a door can accept a HasDoor
(or just directly accept the Door
object) and call open, close, etc.
No duplicated code, full flexibility.
If you need your Door
to call methods back in A
and B
then create the Door
class as abstract and implement it in A
and B
as an anonymous inner class. The abstract methods will be called from Door
and then you can do whatever processing is needed in A
and B
when those methods are called.
For example class A becomes:
class A implements HasDoor {
private Door door = new Door() {
@override void notifyDoorChanged(boolean closed) {
// The door is telling us its been opened or closed
}
}
@override
public Door getDoor() {
return door;
}
}
Where door is:
public abstract class Door {
boolean closed;
abstract notifyDoorChanged();
public void close() {
closed = true;
notifyDoorChanged(closed);
}
// etc
}
Note that this is similar to the strategy pattern - but its not quite the same. The Strategy pattern has one master object and then you plug in multiple strategies (i.e. different forms of Door). This has one Door and multiple other objects using the same type of Door, although you could extend it to use the Strategy pattern and have multiple door implementations very easily.