4.1 What's aspect-oriented programming (什么是面向切面编程)
4.1 What's aspect-oriented programming (什么是面向切面编程)
在早期,切面帮助模块化横切关注点。近来,横切交叉点可以描述为应用程序中任何在多个地方使用的功能。例如安全是一个横切关注点,在应用程序的许多方法中都需要应用到安全规则。
如图4.1 描述了横切关注点
图4.1 代表了一个典型的分割为模块的应用程序。每个模块的主要关注都只是提供特定领域的服务。但是每个模块都需要一些类似的辅助功能,例如安全和事务管理。
在面向对象中,常见的用来重用功能的技术是应用继承或委托。但是如果在应用程序中使用过多类似的基类,继承可能会导致脆弱的对象体系。而委托太笨重了,由于委托必然导致委托对象复杂的调用。
在大多数情况下,切面可以提供一种整洁实现来替代继承和委托。使用AOP,你仍然需要在一个地方定义相同的功能,但是你可以生命定义如何和在哪里应用这个方法,而无需修改需要新增功能的类。横切关注点现在可以被模块化在一个成为切面的类中。这有两个好处。首先,每个关注点的逻辑都在一个地方,而不是分散在代码中。其次,由于服务模块只包含主要的关注点(或核心功能)的代码,而其他关注点被移动到了切面,所以代码变得更整洁了。
As stated earlier, aspects help to modularize cross-cutting concerns. In short, a cross-cutting concern can be described as any functionality that affects multiple points of an application. Security, for example, is a cross-cutting concern, in that many methods in an application can have security rules applied to them. Figure 4.1 gives a visual depic-tion of cross-cutting concerns.
Figure 4.1 represents a typical application that’s broken down into modules. Each module’s main concern is to provide services for its particular domain. But each module also requires similar ancillary functionalities, such
as security and transaction management.
A common object-oriented technique for reusing common functionality is to apply inheritance or delegation. But inheritance can lead to a brittle objec t hierarchy if the same base class is used throughout an application,
and delegation can be cumbersome because complicated calls to the delegate object may be required.
Aspects offer an alternativ e to inheritance and delegation that can be cleaner in many circumstances. With AOP, you still define the common functionality in one place, but you can declarativ ely define how and where this functionality is applied without having to modify the class to whic h you’re applying the new feature. Cross-cutting concerns can now be modula rized into special classes called aspects . This has two benefits. First, the logic for each concern is now in one place, as opposed to being scattered all over the code base. Second, our service modules are now cleaner since they only contain code for their primary concern (or core functionality) and second-ary concerns have been moved to aspects.
浙公网安备 33010602011771号