0

As far as I know the singleton design pattern should be used when a class must have at most one instance. In my project, which is an e-shop, I use entities like 'User', 'Order', 'Cart' and I think that the singleton pattern is the case for each one of my previous entities. For example, the following scenario is very common for an e-shop.

One User has one Cart

One Cart makes one Order.

Have I misinterpret the Singleton pattern?

1
  • You have to consider the technical scope of a Singleton, not the business scope (like the 1:1 relationship User<->Cart). The technical scope is, for instance, a Java Virtual Machine, which would mean that you could have just one user in your application, or per class-loader, if you like to go into detail.
    – Jan B.
    Commented May 18, 2018 at 18:47

3 Answers 3

3

Yes, you misinterpreted the pattern.

You have 1:1 relationships (which seems correct), but designing e.g. the user as a singleton would mean that you could only have one customer in your shop.

The singleton pattern might make sense for the authentication service as you probably want one single instance to answer if a given user has a valid session (in contrast to having multiple service instances where the user might have to log in to every single one).

0

I believe the Singleton pattern is used for when you want an object to be the same across your entire program. For example, with e-shopping, the singleton might be the catalog and inventory. You will naturally have many users, and while each one at a given time might have one cart and one order, you might store a user's previous orders, so users could have multiple orders. Regardless, if you made a user's cart a singleton across the whole program, then every shopper would see the same cart.

0

From what I understand, Singleton is used for an object that you don't want to be instantiated more than once; e.g. a list of all active/logged-in User objects in your case.

From the server's point of view, there are multiple Users, multiple Carts and multiple Orders so doesn't make sense to use Singleton for these classes.

From the client's side however, yes there will only be 1 User and 1 Cart active at any given time. Singleton may be used here but still doesn't really match with Singleton's intended use case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.