我有一些 BaseClass用一些方法 void doSomething() .
foSomething有不同的方法它们由 SubClass1 实现, SubClass2和 SubClass3 .
现在我想添加一个Boolean active属性(property)给BaseClass这样当doSomething在一个实例上调用它只会返回而不做任何事情。
我知道我可以编码 BaseClass有 doSomething()看起来像:
Void doSomething(){
if (this.getActive()) actuallyDoSomething();
}
然后 @Override actuallyDoSomething()而不是 @Override doSomething()在子类中。
但感觉不对...从某种意义上说,已经同意子类应该为 doSomething() 提供实现。他们不知道actuallyDoSomething() .
我也可以让每个子类添加一个 if (!this.getActive()) return;在其实现之初 doSomething()但这也似乎是错误的,因为它的通用功能我更愿意保持通用。
执行此操作的常见/最佳实践方法是什么? 不改子类能做到吗?
更新
Q 的重点不是设计此类功能的正确方法(这很简单), 但如何在不破坏任何内容的情况下将此类功能添加到现有场景中。
active默认情况下为真,但如果有人调用 setActive(false),则希望在任何所述子类的任何实例上然后它将变为非 Activity 状态并连续调用 .doSomething()不会做任何事...
最佳答案
您想使用来自 AspectJ 的 @Around 建议并执行如下操作:
// Let subClass instances run normally...
cec.setActive(true);
letThemDoSomething("BEFORE", sbc1, sbc2, sbc3);
// Now change existing scenario...
cec.setActive(false);
letThemDoSomething("AFTER", sbc1, sbc2, sbc3);
这将输出:
BEFORE ======
SubClass1: doSomething() called.
SubClass2: doSomething() called.
SubClass3: doSomething() called.
AFTER ======
Blocking instance<1> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
Blocking instance<2> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
Blocking instance<3> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
在接下来的几行中,我将描述如何使用注释实现这一点。
我也会在这里使用 Spring。它有助于使配置更快、更容易。
工具和依赖项
Java 7、AspectJ 1.7.4、Spring 4.0.2
项目结构
pom.xml
<project ...>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>4.0.2.RELEASE</spring.version>
<aspectj.version>1.7.4</aspectj.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</project>
BaseClass.java
public class BaseClass {
public void doSomething() {
}
public void say(String msg) {
System.out.println(msg);
}
}
SubClassN.java
public class SubClassN extends BaseClass {
private Integer index;
public SubClassN(Integer index) {
this.index = index;
}
@Override
public void doSomething() {
say("SubClass" + index + ": doSomething() called.");
}
public Integer getIndex() {
return index;
}
}
这是 AspectJ 及其 @Around 建议。我们将首先要求 AsjectJ 在调用任何 doSomething 方法时调用一个特定方法。 doSomething 可以在 BaseClass 或其任何子类中的任何位置。
此特定方法 称为changeExistingScenario。它可以有任何名称。这里重要的是放在上面的注释。
关于@Around 值的一句话:
execution(* my.first.spring.aop.aspectj.BaseClass.doSomething(..))
这个表达式简单地表明了我们想要拦截的方法签名模式。
它会拦截 BaseClass 或子类中的任何 doSomething 方法,无论
多少个参数、返回类型和访问修饰符。
有关详细信息,请参阅:http://guptavikas.wordpress.com/2010/04/15/aspectj-pointcut-expressions/
ChangeExistingCode.java
@Aspect // Mark ChangeExistingCode as the class for modifying the code
@Component
public class ChangeExistingCode {
private boolean active;
public void setActive(boolean active) {
this.active = active;
}
/**
*
* This method will be called by AspectJ anytime a `doSomething` method is called.
*
* This will give us a chance to decide whether the `doSomething` method should
* be called or not.
*
*/
@Around("execution(* my.first.spring.aop.aspectj.BaseClass.doSomething(..))")
public void changeExistingScenario(ProceedingJoinPoint joinPoint) throws Throwable {
// Is active ?
if (active) { // Yes, let doSomething() run as usual
joinPoint.proceed();
} else {// No, block doSomething() invokation
Signature s = joinPoint.getSignature();
System.out.format( //
"Blocking instance<%d> method: %s#%s(%s) !!\n", //
((SubClassN)joinPoint.getTarget()).getIndex(), //
s.getDeclaringTypeName(), //
s.getName(), //
Arrays.toString(joinPoint.getArgs()) //
);
}
}
}
主.java
@Configuration // Mark the Main class as the class where Spring will find its configuration
@ComponentScan // Ask Spring to look for other components within the Main class package
@EnableAspectJAutoProxy // Let Spring auto configure AspectJ aspects for us...
public class Main {
private static int subClassCounter;
public static void main(String[] args) {
subClassCounter=0;
GenericApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
SubClassN sbc1 = context.getBean(SubClassN.class);
SubClassN sbc2 = context.getBean(SubClassN.class);
SubClassN sbc3 = context.getBean(SubClassN.class);
ChangeExistingCode cec = context.getBean(ChangeExistingCode.class);
// Let subClass instances run normally...
cec.setActive(true);
letThemDoSomething("BEFORE", sbc1, sbc2, sbc3);
// Now change existing scenario...
cec.setActive(false);
letThemDoSomething("AFTER", sbc1, sbc2, sbc3);
context.close();
}
private static void letThemDoSomething(String prefix, SubClassN... existingClasses) {
System.out.format("%s ======\n", prefix);
for (SubClassN subClassInstance : existingClasses) {
subClassInstance.doSomething();
}
System.out.println();
}
@Bean // Tell Spring to use this method for creating SubClassN instances
@Scope(BeanDefinition.SCOPE_PROTOTYPE) // Scope prototype force creation of multiple instances
private static SubClassN buildSubClassN() {
subClassCounter++;
return new SubClassN(subClassCounter);
}
}
输出
BEFORE ======
SubClass1: doSomething() called.
SubClass2: doSomething() called.
SubClass3: doSomething() called.
AFTER ======
Blocking instance<1> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
Blocking instance<2> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
Blocking instance<3> method: my.first.spring.aop.aspectj.SubClassN#doSomething([]) !!
Download full code: http://www.filedropper.com/advicearoundsample
Other useful resources that helped writing this answer
关于java - 如何在不修改子类的情况下添加对现有子类中方法调用的控制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21883856/
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以