在MySQL数据库表中反映装饰器模式 [英] Reflecting a decorator pattern in mysql database table

查看:116
本文介绍了在MySQL数据库表中反映装饰器模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mysql数据库和java.我对装饰器模式的理解是,它允许非常灵活的运行时,因为您可以随意分配任意数量的装饰器,直到获得所需对象的行为或表示.以前我已经成功地编程了几个装饰器,现在我想将装饰对象的状态存储到数据库中(最好是mysql).例如:

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)将该饮料编码为一个json字符串,然后将其转储到数据库中,并假设我的数据访问对象可以对此进行解码.

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)尝试预期对饮料的所有可能的修改,并为每种饮料做一列,每当有人想出一种新的饮料添加项时,我都必须更改架构.

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.

推荐答案

为此,请尝试使用3个表,一个用于配料,一个用于订单,以及两个表之间的查找表.每次创建订单时,您都会在订单中添加一行,并在orders_ingredients中添加很多行

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)
);

这篇关于在MySQL数据库表中反映装饰器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆