Page 1 of 1

Need advice on which design pattern to use

Posted: Mon Feb 17, 2014 11:23 pm
by Luke
I have a series of classes that make up a composite structure. I'm going to simplify the interface just to make it easier to understand. Let's say I have components and properties. Components can have sub-components and properties. Sometimes certain components require certain sub-components. Sometimes certain components require certain properties. Sometimes components have required properties depending on whether certain other properties are set or have certain values. So, basically I have to define rules that specify when properties are required and when they aren't. Here is an example structure of components/properties:

Code: Select all

/MyLibrary
    /Component
        Alarm.php
        Calendar.php
        Event.php
        Todo.php
        Entry.php
    /Property
        Method.php
        Version.php
        ProdId.php
        Start.php
        End.php
        Description.php
        Summary.php
        Title.php
Calendar components ALWAYS require Version and ProdId properties. Event components can optionally have Summary, Description, and Title properties. They are REQUIRED to have a Start property if they are the sub-component of a Calendar component that DOESN'T have a Method property. Entries ALWAYS require a Title and Description property. Alarm components can only be sub-components of Event and Todo properties, but if an Event or Todo component has an Alarm sub-component, it MUST also have a Start and End property.

So you can see how sometimes the specifications for required properties/components can be either very straightforward or somewhat complex. At first I was just going to add a $requiredProperties property on the component class, but after finding out that the specifications for when properties are required can be much more complex than I first thought, it became clear that I needed something a little more complex to define required properties. I have been looking at my Gang of Four design patterns book and the only design pattern I have found that seems even somewhat close to what I need is the decorator pattern. Can anybody think of a good way to define which properties are required and when? I am really struggling with this...

Re: Need advice on which design pattern to use

Posted: Tue Feb 18, 2014 5:47 pm
by Christopher
Sounds more like the Strategy pattern where you would base what properties and/or sub-components are needed base on the Component type and other factors.

Re: Need advice on which design pattern to use

Posted: Tue Feb 18, 2014 11:32 pm
by Luke
Yeah I had considered Strategy briefly but it didn't seem to quite fit. I'll take a look again and see what I think. Thanks, man :)

Re: Need advice on which design pattern to use

Posted: Tue Jun 24, 2014 6:36 am
by josephwoodland
Thanks for sharing this information .