GurdeepS
GurdeepS

Reputation: 67223

Coding classes with the same behaviour + unique behaviour

I have a set of classes which have similarities and differences. They derive from an interface, which defines the unique behaviour amongst these different classes, and a base class to call the common functionality in the several classes.

Is there a design pattern which governs how these sort of classes are created? Is it acceptable to use a base class and interface together for this design challenge (several classes all with the same logic + unique behaviour).

Thanks

Upvotes: 1

Views: 276

Answers (3)

Ozan
Ozan

Reputation: 4415

If you don't use the base class for a common interface but common behavior only you don't need to derive from it but instead make it a member. That way you can assign behavior dynamically, if need arises.

public class behavior
{
   private void Login();
}

public class concrete1: behavior, IWebApplication
{
  public void Dosomething {Login; ... }
}

becomes

public class behavior
{
   public void Login();
}

public class concrete: IWebApplication
{
  private mBehavior;
  public concrete(behavior aBehavior): mBehavior(aBehavior) {if (aBhavior == 0) mBehavior = new behavior} ;

  public void Dosomething {mBehavior.Login; ... }
}

Now you derive from behavior if you want to change behavior implementation only.

Upvotes: 0

Mark Bessey
Mark Bessey

Reputation: 19782

It's not clear to me what advantage your interface is giving you. Having classes that have some similar behavior and some different behavior is the essence of inheritance. You can put all the common behavior in a base class, then override the places where it needs to be different in each subclass.

I suppose if your language doesn't support abstract base classes, then having a base class and an interface would make sense. Can you give an example of what it is you're trying to do?


Your ABC can be something like:

public abstract class A
{
    public virtual void EverybodyDoesThisTheSame();
    public abstract void ThisIsDifferentForEach();
}

Then, in the derived classes, you just need to inplement ThisIsDifferentForEach(), and they can all use the inherited version of EverybodyDoesThisTheSame().

Upvotes: 1

dariol
dariol

Reputation: 1979

Specification pattern will help you.

http://en.wikipedia.org/wiki/Specification_pattern

Upvotes: 0

Related Questions