Reputation: 2675
I'm learning about programming patterns and for our final assignment we were asked to build an "online store".
I was thinking about how to model the User
which can either be Admin
or Customer
.
I thought about the Strategy pattern to model each individual User
with their particular behaviors.
They don't share any behaviors so far, so the Admin
can't addToCart
and Customer
can't registerNewProduct
.
However, they could share behaviors / methods as the system evolves!
Furthermore, the User
won't change it's type in run-time. I.e., once you log in as Customer, you can't log back in as Admin.
Even if they shared behaviors such as seeProductList
, this could be achieved with good ol' inheritance, right?
Should I use Strategy, Inheritance or would you recommend another pattern?
If you need more information, please let me know! :)
Thanks in advance.
Upvotes: 0
Views: 375
Reputation: 7838
I think you've tumbled into the puzzle
of patterns.
Actually there is no obvious reason to use Strategy
here. Let's first see what's the most outstanding feature of Strategy
.
Strategy is a behavioral design pattern that lets you define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
As I see it, if you wanna use different methods/algorithms
to solve the same problem, you would use Strategy
.
A demo would be parse(File file)
and there are several methods to parse the file for different scenarios.
parseInParallel(File file) // when in single-user system;
parseSequatially(File file) // multi-user system;
You see, they're achieving the same target but use different methods.
In your case, I would like to recommend inheritance
since there are lots of common features between Customer and Admin, which might include:
But as you already mentioned, a lot of methods are different. So you can add them separately in the subclass
so basically you will have Person
, Customer
and Admin
.
Person
has the most basic information and method, Customer
has the methods and new fields related to customers and Admin
similarly.
Upvotes: 2