20

An object-oriented program usually contains different types of objects, each corresponding to a particular kind of complex data to manage, or perhaps to a real-world object or concept such as a bank account, a hockey player, or a bulldozer.

Modular programming (also called "top-down design" and "stepwise refinement") is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.

Differences that I can think of are that you can have more than one objects on a class, where as in modular programming you are supposed to have only 1 module (1 object) for one specific thing.

Here is an example (the way I understand it)

Consider you have a program. A few input fields and a button. Then some calculations are made and the program outputs something.

This program can have 2 modules: The input/output one and the calculation one.

However I don't see why the program can't have a layout (a class containing all the objects that will be shown on the screen) and a logic part (which can be a class or a function depending on the depth of the calculations).

Is this example "correct" in temrs of both modular and object programming ? Can modular and oop be used together ? And what is the big difference between these two paradigms/programming styles?

4

1 回答 1

26

您的模块可以实现为类,这确实是正确的。但是,模块是逻辑上独立的程序片段,因此将它们作为类是没有意义的,因为您可以拥有一个类的许多不同对象。如果我要编写一个模块化系统并为模块使用类,我会将它们全部设为单例。

在您的示例中,面向对象的编程中,您将拥有定义输入字段和按钮的类,或者可能是用作计算器的类。您甚至可以更深入地定义一个 Calculator 接口,该接口可以实现为 SumCalculator、ProductCalculator 等,甚至可以放入一些工厂,以便用户可以在您的程序执行的不同计算之间进行选择。是的,您可以拥有单例类,例如 LayoutModule(将跟踪 InputField 和 Button 类型的对象)和 LogicModule(将跟踪 Calculator 实现)。

模块化编程仅意味着您拥有这两个(或更多)模块,但没有说明它们如何实现它们所实现的目标。这些模块可以使用或根本不使用面向对象的方法,并使用过程 C 风格的编程。您通过类​​描述模块化编程的方式只是分离模块的一种方式。例如,您可以将它们分隔为类,也可以将它们分隔为跨多个编译单元的函数。这是你的选择。

面向对象编程意味着您的程序是面向对象的。它没有说明应用程序中的模块,但要求表示应用程序中某些想法的逻辑部分通过类和对象建模。

因此,这两种方法可以一起使用,当您决定模块化时,面向对象的选择通常会强加给您这些模块是通过类及其关系定义的。

于 2013-08-03T22:22:53.587 回答