上一篇我们共同学习了以Callable接口的方式实现多线程,本篇我们来学习和类比多线程与代理模式的相似之处,以及学习Java8之后出现的lamda表达式。
Lambad表达式的作用:
代码如下(示例):
主类:StaticProxy类
public class StaticProxy {
public static void main(String[] args) {
WeddingCompany weddingCompany = new WeddingCompany(new You());
weddingCompany.HappyMarry();
}
}
接口:Marry接口
interface Marry{
public void HappyMarry();
}
真实类:You类
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("我要结婚了。");
}
}
代理类:WeddingCompany类
class WeddingCompany implements Marry{
private Marry targe;
public WeddingCompany(Marry targe) {
this.targe = targe;
}
@Override
public void HappyMarry() {
before();
targe.HappyMarry();
after();
}
private void before() {
System.out.println("结婚之前,布置现场");
}
private void after() {
System.out.println("结婚之后,收份子钱");
}
}
运行结果:
代码如下(示例):
Ilike接口
//函数类接口
interface ILike{
void Lambda();
}
Like类
//1.实现类
class Like implements ILike{
@Override
public void Lambda() {
System.out.println("i like lambda1");
}
}
TestLambda01类
public class TestLambda01 {
//2.静态内部类
static class Like1 implements ILike{
@Override
public void Lambda() {
System.out.println("i like lambda2");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.Lambda();
like = new Like1();
like.Lambda();
//3.局部内部类
class Like2 implements ILike{
@Override
public void Lambda() {
System.out.println("i like lambda3");
}
}
like = new Like2();
like.Lambda();
//4.匿名内部类,没有类的名字,必须借助接口或者父类。
like = new ILike(){
@Override
public void Lambda() {
System.out.println("i like lambda4");
}
};
like.Lambda();
//5.lambda简化
like = ()->{
System.out.println("i like lambda5");
};
like.Lambda();
}
}
运行结果: