问题
I am working with a mysql database and java. My understanding of the decorator pattern is that it allows for very flexible runtime because you can just assign as many decorators as you want until you get the behaviour or representation of the object that you want. I have successfully programmed several decorators before, now I would like to store the state of my decorated object into a database (preferably mysql). For example:
Suppose I am coding a system for a coffee shop and my model for representing the cost of beverages uses a decorator (ie. concrete object is espresso and it can be decorated with milk, sugar, whip cream, syrup and whatever else they put in coffee these days.) Furthermore, suppose I cannot at this time anticipate how many different ingredients I can have in my coffee in the future (maybe someday people will want jelly beans in their coffee, but I don't know that yet)
Now I want to record every time someone buys a drink, and keep track of the ingredients that were used. What is the best way to design my database schema so that it can handle new ingredients as they appear. I currently have two ideas, neither of which seems like the correct way to go about it:
1) Encode the drink as a json string that and just dump it in the database, assume my data access objects can handle decoding this.
2) Try to anticipate all possible modifications to the drinks and make columns for each of these, every time someone comes up with a new beverage add on I have to alter the schema.
There must be a better approach than either of these.
回答1:
Try using 3 tables for this, one for the ingredients, one for the order, and a lookup table between the two. Each time an order is created you add one row to orders and many rows to orders_ingredients
create table orders {
order_id int AUTO_INCREMENT PRIMARY KEY,
order_name
);
create table orders_ingredients {
order_id references orders(order_id)
ingredient_id references ingredients(ingredient_id)
);
create table ingredients {
ingredient_id int AUTO_INCREMENT PRIMARY KEY,
ingredient_name varchar(255)
);
来源:https://stackoverflow.com/questions/18278465/reflecting-a-decorator-pattern-in-mysql-database-table