这是一个常见的和/或命名的OOP模式? [英] Is this a common and/or named OOP-pattern?

查看:123
本文介绍了这是一个常见的和/或命名的OOP模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我经常使用的这种模式是否常见,并有一个名称:




  • 一个算法是一个类

  • 其参数通过类

  • 的构造函数传递,调用无参数运行方法触发器

  • 通过调用getter方法获取结果



一个示例(在Python中为了简单起见):

  class MyAlgorithm:

def __init __(self,input,param1, param2):
self.param1 = param1
self.param2 = param2
self.input = input

def run(self):
..
return self

def getResultA(self):
...

def getResultB(self):
...

作为第二个问题:这种模式的优缺点是什么?有没有一个很好的理由有一个单独的运行 -method而不是让构造函数进行计算?

解决方案

它是命令模式,其中意图是将主要操作一些类(具体Command类)从其消费者(CommandHandler)。总而言之,执行 someCommandObject.run(); 的客户端类没有任何方法参数,因此该具体类中的方法实现可以自由地实现任何所需的操作到那个特定的类。所以客户端类可以自由地执行 anyCommandObject.run(); 方法,因为它们的方法声明对于任何类型的参数都不是刚性的。



我们在Java线程中的 Thread.run(); 中也是一样的。



< blockquote>

有没有一个很好的理由有一个单独的运行方法,而不是
,构造函数执行计算?


是的。构造函数应该永不有明确的计算。构造函数的目的只是简单地构造对象,而不是发现任何行为。如果你想公开他们,那就是为什么方法在那里。


I wonder whether this pattern that I have frequently used is common and has a name:

  • an algorithm is a class
  • its parameters are passed via the constructor of the class
  • calling a parameter-less run method triggers the computation
  • the result(s) are fetched by calling getter methods

An example (in Python for simplicity):

class MyAlgorithm:

    def __init__(self, input, param1, param2):
        self.param1 = param1
        self.param2 = param2
        self.input = input

    def run(self):
        ...
        return self

    def getResultA(self):
        ...

    def getResultB(self):
        ...

As a second question: What are the pros and cons of this pattern? Is there a good reason to have a separate run-method rather than having the constructor do the computation?

解决方案

It is command pattern, where the intention is decoupling the implementation of the main operation of some classes(concrete Command classes) from its consumer(CommandHandler). In summary a client class who executes someCommandObject.run(); is free of any method arguments, hence the method implementation inside that concrete class can freely implement any desired operation which is specific to that particular class. So the client class can freely execute anyCommandObject.run(); methods, since their method declarations are not rigid with any typed parameters.

It is the same thing we are having in Thread.run(); in Java Threads.

Is there a good reason to have a separate run-method rather than having the constructor do the computation?

Yes. The constructor should never have explicit calculations. The purpose of a constructor is simply construct the object, not to uncover any behaviors. If you want to expose them, that's why methods are there.

这篇关于这是一个常见的和/或命名的OOP模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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