tags:

views:

82

answers:

1

I have been scratching my head for a while thinking about the best way to remove singletons I stupidly added in the first place. For background, this application is a stock portfolio tracker. I currently have three classes which I thought would be the only instance:

  1. Prices (a class holding a list of historical prices, dividends, splits)
  2. Portfolios (a class managing a collection of portfolio objects with some useful wrapper functions)
  3. Queries (a class that reads and writes to the database)

To meet user requests, I am adding in the ability to open and save from multiple databases. Each database (Queries class) will theoretically be passed into a Portfolios and Prices' constructor to load the data.

The issue I am facing is that all 3 classes are interconnected. If I open C:\database1.sqlite, I shouldn't be able to mix and match the Prices and Portfolios from C:\database2.sqlite. Also, any edits must be saved down to the proper database.

My initial thought is to create a context object which consists of these classes and pass this around. However, reading http://stackoverflow.com/questions/986865/can-you-explain-the-context-design-pattern-a-bit/986947, I don't think this is the right solution.

How can I remove the singletons, but still keep integrity between the objects? Thanks.

+2  A: 

I would consider what changes you would make to move from "plurals" to "singulars." It will be a lot easier to reason about your system if your objects are a thing rather than some number of things.

E.g.

class Price;
class Portfolio;
class Query;

If necessary, you can always add later:

typedef std::vector<Price> Prices;
typedef std::vector<Portfolio> Portfolios;
typedef std::vector<Query> Queries;

but my humble opinion is that you should probably work out the interactions that you want between single instances of these things and then go to the interactions you want when you have one-to-many associations (i.e. can one instance of those classes refer to multiple instances of another?), and then define those explicitly.

Basically, strive to make reasoning about the interactions simple. You may have a number of Prices and Portfolios, but it's too hard to keep in mind the operations that work on one instance versus operations that work on several instances so split those differences and keep an instance of a thing simple and obvious.

dash-tom-bang