如何在 Web MVC 框架中正确实现策略模式?
在我的 Django 应用程序中,我有一个模型(我们称之为 Foo),其中有一个名为“type”的字段。 我想使用 Foo.type 来指示 Foo 的特定实例是什么类型(可能的选择是“数字”、“日期”、“单行文本”、“多行文本”等) 。
我希望“类型”字段最终影响两件事: 值从普通类型转换为文本的方式(例如,在“Date”中,它可能是 str(the_date.isoformat())
),以及值从文本转换的方式到指定的类型(在“日期”中,它可能是datetime.date.fromtimestamp(the_text)
)。
对我来说,这似乎是策略模式(我可能完全错了,如果我错了,请随时纠正我)。 我的问题是,在 Web MVC 框架中编写此代码的正确方法是什么?
在客户端应用程序中,我将创建一个带有抽象方法“serialize()”和“unserialize()”的 Type 类,在 Type 的子类(例如 NumberType 和 DateType)中重写这些方法,并动态设置“type “在运行时将新实例化的 Foo 的字段转换为适当的 Type 子类。
在网络框架中,这对我来说并不那么简单。 现在,最有意义的方法是将 Foo.type 定义为小整数字段并定义一组有限的选择(0 =“数字”,1 =“日期”,2 =“单行文本”,等)在代码中。 然后,当实例化 Foo 对象时,使用 Factory 方法查看实例的“type”字段的值并插入正确的 Type 子类(如上段所述)。 Foo 还将具有 serialize() 和 unserialize() 方法,它们将直接委托给插入的 Type 子类。
这个设计听起来怎么样? 我以前从未遇到过这个问题,所以我很想知道其他人是否也遇到过这个问题,以及他们是如何解决的。
In my Django app, I have a model (lets call it Foo) with a field called "type". I'd like to use Foo.type to indicate what type the specific instance of Foo is (possible choices are "Number", "Date", "Single Line of Text", "Multiple Lines of Text", and a few others).
There are two things I'd like the "type" field to end up affecting; the way a value is converted from its normal type to text (for example, in "Date", it may be str(the_date.isoformat())
), and the way a value is converted from text to the specified type (in "Date", it may be datetime.date.fromtimestamp(the_text)
).
To me, this seems like the Strategy pattern (I may be completely wrong, and feel free to correct me if I am). My question is, what's the proper way to code this in a web MVC framework?
In a client-side app, I'd create a Type class with abstract methods "serialize()" and "unserialize()", override those methods in subclasses of Type (such as NumberType and DateType), and dynamically set the "type" field of a newly-instantiated Foo to the appropriate Type subclass at runtime.
In a web framework, it's not quite as straightforward for me. Right now, the way that makes the most sense is to define Foo.type as a Small Integer field and define a limited set of choices (0 = "Number", 1 = "Date", 2 = "Single Line of Text", etc.) in the code. Then, when a Foo object is instantiated, use a Factory method to look at the value of the instance's "type" field and plug in the correct Type subclass (as described in the paragraph above). Foo would also have serialize() and unserialize() methods, which would delegate directly to the plugged-in Type subclass.
How does this design sound? I've never run into this issue before, so I'd really like to know if other people have, and how they've solved it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以查看 django ORM 提供的继承内容。 这将为您提供实际子类化模型的方法,无论模型是什么,带有鉴别器、不同的表等
。
You could look through inheritance stuff that the django ORM provides. This will give you ways to actually subclass whatever the model is w/ discriminators, different tables, etc.
etc...