简体   繁体   中英

Inheritance vs. Strategy Pattern

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. Ie, 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.

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.

Strategy - 1:

parseInParallel(File file) // when in single-user system;

Strategy - 2:

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:

  1. name;
  2. age;
  3. email;
  4. gender/sex;
  5. address;
  6. telephone;
  7. and more other related to person...

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.

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