工厂方法-应用程序类是否需要抽象? [英] Factory method - Does application class need to be abstract?

查看:111
本文介绍了工厂方法-应用程序类是否需要抽象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Erich Gamma的GOF设计模式书说:

Erich Gamma's GOF design pattern book says:

应用程序一词可以自行创建多个文档,如下所示:

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

似乎一个应用程序可以创建多个文档.
在哪种情况下,我需要将Application类抽象化然后从中派生?

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?

推荐答案

抽象应用程序类不是工厂模式的本质,但是我们需要了解其背后的意图.相同的意图可以通过抽象的Plugin类来实现(在下面的示例实现中).

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

任何将对象创建推迟到需要处理的对象的子类的类都可以看作是Factory模式的示例.

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.

GOF中描述的工厂模式提供了可能实现文档应用程序的示例,用于理解但并非特定于特定的Word应用程序,但是我们仍然可以在基于factory method的设计基础上进行设计

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

对于当前的Word应用程序,可能的设计可能类似于基于插件的设计,其中我们可以有多个插件,并且每个插件都可以添加到应用程序中.实体(在本例中为Document)的创建是由每个插件完成的.

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.

这篇关于工厂方法-应用程序类是否需要抽象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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