Design Patterns – How to Use the Same Behaviour in Different Classes

design-patternsobject-oriented

I have a behaviour that I'd like to use in different classes. Those classes are unrelated to each other (no inheritance). I'm using AS3, where multiple inheritance is not possible.

I could use an interface but then I'd have to rewrite the same implementation every time, which is basically what I'm doing now (but without the interface).

As en example I have many situations where I have an icon and a text label. In buttons, signs, etc. I'd like to centralise the alignment behaviour between the icon and the label.

What is the best OOP pattern for that?

Best Answer

The Strategy pattern is what I would use for this (encapsulating an algorithm). How the alignment is done is something that can be configured at runtime. There are also lots of different ways of aligning elements so you encapsulate them behind an interface. The example below is one way you could use strategy pattern with your Aligner class.

class Panel
{
    UIElement[] Children;
    IAligner Aligner;

    public SetAlignment(IAligner aligner)
    {
        this.Aligner = aligner;
    }

    public void Render()
    {
        Aligner.Align(Children)
        Display(Children)
    }
}

interface IAligner
{
    void Align(UIElement[] elements)
}

class LeftAligner : IAligner
class RightAligner: IAligner
class CenterAligner: IAligner
Related Topic