I have a question. I need to create a little thing to do with products. Now I can have say 7 different types of products. Some are subtypes of others e.g.

Cars
 - Vans
   - petrol
   - diesel
 - City
 - Hatchback
 - Saloon
 - Estate
   - petrol
   - diesel

Now, for the sake of the argument all my City, Hatchback and Saloon cars are hybrid/gas/whatever and I do not plan to sell petrol and diesel ones. However there is a possibility that I may have petrol and diesel saloon cars sometime in the future, but it's not like I am going to have 20+ types of products. If it is going to go up I will have probably 2-3 more types.

From what I understand Prototype Pattern may be good one here for I will be able to avoid duplication between estate->petrol and van->petrol ... but then again Van cars will have different characteristics than say city car e.g. maximum loading dimensions.

I have been reading extensively about design patterns and one thing I remember for certain is not to use pattern when you don't need it. Now the question is - do I need it?

Thanks!

有帮助吗?

解决方案

The Decorator Pattern is probably the most straight forward one to use and would be a good one to extend concrete objects functionality and/or characteristics.

Here is some light reading: Head First Design Patterns - CH3 pdf

FYI, couple must have's for learning and referencing design patterns regardless your language of choice:

1) Head First Design Patterns

2) Patterns for Enterprise Application Architecture

3) Design Patterns: Elements of Reusable Object-Oriented Software

And sites:

1) DoFactory

2) StackOverflow Design Patterns Newbie

There are a few others, I'll have to dig them up.

其他提示

Does each type of car requires different behaviour? A petrol van acts different from a diesel van? A Saloon has to behave different than an Estate?

If I understand correctly, you need something like that

public enum FuelType
{
     Petrol,
     Diesel
}

public class Car
{
   public string Name {get;set;}
   public FuelType Fuel {get;set;}
}

public class Van:Car { } 
public class CityCar:Car { }

If the characterstics of a Van are just different values than a Car, you don't need subclassing, you need to change just a property value. A Van for example should have other properties or a differnt implementation of methods to be eligible for subclassing.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top