Welcome

首页 / 软件开发 / 数据结构与算法 / 用AspectJ实现工厂方法模式

用AspectJ实现工厂方法模式2011-12-28工厂方法模式根据产品的等级结构使用对应的工厂来创建特定的产品,它一般包括抽象工厂、具体工厂和抽象产品、具体产品,每一个特定工厂用于创建一个对应的产品。模式的简易UML图例如下

下面是使用AspectJ实现的工厂方法模式UML图

抽象方面FactoryMethodProtocol很简单只定义了抽象pointcut createMethod用于捕捉特定应用的创建方法(也可以省略)。

FactoryMethodProtocol抽象方面public abstract aspect FactoryMethodProtocol ...{abstract pointcut createMethod();}FactoryMethodImpl.javapublic aspect FactoryMethodImpl extends FactroyMethodProtocol...{public Fruit FruitGardener.factory()...{//为创建接口定义工厂方法return null;}//Inter-type声明具体创建类并实现创建接口declare parents : AppleGardener implements FruitGardener;declare parents : GrapeGardener implements FruitGardener;//指定createMethod捕捉FruitGardener及其子类的创建方法pointcut createMethod() : call(Fruit FruitGardener+.factory());Fruit around(FruitGardener gardener) : target(gardener) && createMethod()...{return chooseGardener(gardener);//工厂方法返回抽象产品。}private Fruit chooseGardener(FruitGardener gardener)...{if(gardener instanceof AppleGardener)...{return new Apple();}else if(gardener instanceof GrapeGardener)...{return new Grape();}else...{throw new RuntimeException("No such kind of fruit");}}  //声明编译时错误:当客户直接使用new创建具体产品时发生。//目的:强制程序完全按照工厂方法的形式创建产品。//可选为声明警告 declare warning : [pointcut] : [warn msg]declare error : !(within(FruitGardener+) && !createMethod())&&!within(FactoryMethodImpl) && call(Fruit+.new(..)): "You can only create fruits through the method factory provided by FruitGardener and its subclass";}