开发者

How's View gonna know what component to create?

I'm developing this application where you can put text and drawings in a page. My application is in MVC pattern, and I need all the model parts, text and shapes to be of the same notion. They all extend an abstract ReportElement clas, for example.

But the problem is I crate a JPanel for every shape in the page, but to handle text I need to use JTextArea or something. To render the elements the 开发者_如何学运维View directly gets the report elements list from the Model and draws one by one. How can I distinguish a text element without hurting the MVC pattern.

I mean, it's impossible, right? I don't know, any ideas?


I think you're looking for the "Factory Pattern"

You need to have a wrapper method that returns a JComponent based in your own ReportElement conditions.


I would handle this situation by building a factory method that produces the right type of Swing component for any given ReportElement, like this:

public static JComponent buildViewForReportElement(ReportElement element)

Inside this method, you will need to actually inspect the ReportElement objects to see what type of component to build. This inspection might mean checking a field or a flag on each object, or might even mean using instanceof to distinguish different subclasses of ReportElement from one another.

Note that inspecting ReportElement objects like this violates the philosophy of object-oriented programming. A simple "object-oriented" solution would require all of your ReportElement objects to have a buildView() or getView() method, and so your GUI code could just call getView() on every ReportElement without knowing which implementation of getView() was actually being called.

Unfortunately, the object-oriented solution forces you to mix your view code with your model code, and it's good that you are trying to keep the two separate. That's why I would advocate keeping the GUI-building code out of ReportElement objects and instead using a factory method to build the right view for any given ReportElement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜