Factory method - Does application class need to be abstract?

岁酱吖の 提交于 2019-12-11 09:23:54

问题


Erich Gamma's GOF design pattern book says:

Whereas the word application can create several documents on its own as shown below:

It appears that one application can create several documents.
In what kind of case then will I require to make Application class abstract and then derive from it?


回答1:


Application class being abstract is not the essence of factory pattern, but we need to see the intent behind it. The same intent is being fulfilled by abstract Plugin class ( in below example implementation).

Any class deferring the object creation to its sub class for the object it needs to work with can be seen as an example of Factory pattern.

Factory pattern as described in GOF presents an example of possible implementation of document application for understanding but not specific to specific Word application but still we can have a possible below factory method based design

For current Word application a possible design can be similar to plugin based where we can have multiple plugins and each can be added to the application. The entity(in this case Document) creation is done by the each plugin.

If a new type of document is needed then a plugin can be implemented and added to the application.

A possible structure of the code can be like below.

Class Application{
    List<Plugin> plugins ;
    public void addPlugin(Plugin newPlugin){
       plugins.add(newPlugin);
    }
    //more code as per req and features
}

 public abstract class Plugin{
    public abstract Document createNewDocument();
    public void openNewDocument(){
         Document doc = createNewDocument();
         doc.open();// assuming open is a method in Document interface.
           //more code as per req and features
    }
 }

public class PNGPlugin extends Plugin{
     public Document createNewDocument(){
          return new PNGDocument();// Document being the interface for various documents.
     }
       //more code as per req and features
}  

Menu items will in current approach depend upon the list of plugins.




回答2:


The common case would be that the Application and Document abstract classes are provided by the framework that you use (something like Swing or UIKit or Gnome), and your own code would implement them as MyDocument and MyApplication.



来源:https://stackoverflow.com/questions/49109420/factory-method-does-application-class-need-to-be-abstract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!