最近学习了spring的面向切面编程,在网上看到猴子偷桃的例子,觉得这种方式学习比书本上讲解有趣多了,也便于理解。现在就来基于猴子偷桃写个基本的例子。

maven工程:

 

利用例子来理解spring的面向切面编程

1、猴子偷桃子,这里就有两个类出现,一类是猴子,一类是桃子。如果以后需要扩展,来个狼偷羊,怎么办呢?因此为了扩展,可以声明接口Stolen,表现偷的行为。

Stolen接口:

 

package com.test.demo.stolen;

public interface Stolen {
    /**
     * 偷桃子
     * 
     * @date 2014-4-1
     
*/
    public void stolens(String name,Peaces peace);
}

 

猴子需要实现这个Stolen接口,表示猴子具有偷的行为,Monkey类:

 

package com.test.demo.stolenImpl;

import org.springframework.stereotype.Component;

import com.test.demo.stolen.Peaces;
import com.test.demo.stolen.Stolen;

/**
 * 猴子偷桃子
 * TODO Comment of Monkey
 *
 
*/
@Component("monkey")
public class Monkey implements Stolen{

    private String name;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void stolens(String name,Peaces peace){
        System.out.println("猴子 "+name+" 正在偷桃子,桃子是:"+peace.getName()+" 大小:"+peace.getType());
        this.name = name;
    }
}
View Code

相关文章:

  • 2021-11-04
  • 2021-05-07
  • 2021-07-29
  • 2021-11-05
  • 2022-12-23
  • 2021-11-20
  • 2021-05-16
猜你喜欢
  • 2022-12-23
  • 2021-11-30
  • 2021-10-11
  • 2022-12-23
  • 2021-04-27
  • 2021-09-22
相关资源
相似解决方案