Day 21
June 1, 2019.
This is what I learn Java twentieth day.
On this day, I learned the following knowledge.
Static agents
Static agent, is a design pattern.
Static agent is relatively simple, the proxy class by implementing the same interfaces of the target, and maintain a proxy object in the class. By stuffing target object constructor, assigned to the proxy object, the proxy object further performs interface methods implemented and implemented before the interception, the interception required business functions.
As in the following example:
- You (RealSubject): real role
- Wedding companies (Proxy): Agent role, the proxy you, help you deal with the marriage thing
- Married (Subject): interface, the interface can be married
//静态代理
public class StaticProxy {
public static void main(String[] args) {
//代理对象 代理 真实对象
You you = new You();
new WeddingCompany(you).happyMarry();
}
}
//真实对象:你
class You implements Marry{
@Override
public void happyMarry() {
System.out.println("b");
}
}
//代理对象:婚庆公司
class WeddingCompany implements Marry{
//核心:婚庆需要有你这个人,代理对象需要代理一个真实对象
private Marry you;
public WeddingCompany(Marry you) {
this.you = you;
}
@Override
public void happyMarry() {
before();
this.you.happyMarry();
after();
}
private void before() {
System.out.println("a");
}
private void after() {
System.out.println("c");
}
}
//共同的接口:结婚
interface Marry{
void happyMarry();
}
Lambda expressions
Lambda expressions, is an anonymous function. Lambda expressions based on the mathematical calculation of λ named, which directly corresponds to the abstract lambda (lambda Abstraction), is an anonymous function, i.e., without the function of the function name. Lambda expressions can be expressed closures (different from the traditional sense of attention and mathematics).
Lambda expressions are jdk8 new concept, to be used in the function interface (only an abstract interface methods), is converted in the form of an anonymous inner class, you need to have a return value to make the JVM identify which interface. If only pass a parameter, the parameter type, and can also simplify the brackets. If the method body is only one line, you can omit the curly brackets.
Lambda format is as follows:
Here's an example:
public class LambdaTest {
public static void main(String[] args) {
//实现方式1:匿名内部类
ILove iLove = new ILove() {
@Override
public void Love(int a) {
System.out.println(a);
}
};
iLove.Love(1);
//实现方式2:Lambda表达式完整格式
iLove =(int a) -> {
System.out.println("2");
};
iLove.Love(2);
//实现方式3:Lambda表达式缩减格式(省略变量类型)
iLove = a -> {
System.out.println("3");
};
iLove.Love(3);
//实现方式4:Lambda表达式缩减格式(省略变量类型、花括号)
iLove = a -> System.out.println("4");
iLove.Love(4);
}
}
//函数式接口,只有一个方法
interface ILove{
void Love(int a);
}