简体   繁体   中英

what design pattern for building this complex object

I have to create an itinerary object which is essentially made of other components.

These components need to be added in a particular order. I need to make sure when things are added out of order, an exception/error needs to be thrown.

Quick walkthrough:

Itinerary Build-itinerary():

- AddSegment()
- AddBaggagePolicy()
- AddMisc()

Segment AddSegment(...)

- add departure airport
- add arrival airport
- add departure time
- add arrival time
- add duration (total duration)
- add airline

where airport and airline are object types.

Once segments are done, I need to consolidate the segments to yield starting departure to final arrival destination (since there can be multiple hop points from one point to other).

What kind of a pattern can I refer to building this itinerary ?

Looks like it isn't specific enough. At first glance, I might characterise this as a "builder pattern". Many (but not all!) design patterns in Java are workarounds for lack of language features.

In fact, your design there is a code smell, you should not have an apparently arbitrary ordered sequence of steps to construct an object. Instead, define the data, and pass that into the object.

If you must build your object like this, then I would ensure that any code that does this is unit tested using a mock that supports the record and playback style of mocking. (So-called "strict mocks".

And I am not good with design patterns at all: I would start with a Builder Pattern and try to validate each component if it has been added or not. At least this would be my start point : a Builder or a private static inner class.

Try using the Builder Pattern. Also you could look for other variants in the Creational Patterns category.

If you're new to design patterns then take a look at "Head First Design Patterns" - its in google books (I dont know if complete or preview though...)

have fun :)

When I hear the words "building" and "order" then first design pattern that comes to mind is Builder. If you new to Design Patterns then I would recommend you to read "Applied Java Patterns".

Cannot agree with @Arafangion, I belive that ordering of some procedure invocations is sometimes necessary. I would recommend looking into a Factory Method design pattern, from what I remember there is a nice example in Head First Design Patterns book when preparing pizza stuff :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM