Java架构学习(七)注解&自定义注解&设计模式

自定义注解与Java设计模式

一、注解

什么是注解?
    以后开发中,为了简化代码推荐使用大量注解,简化代码。提高开发效率。

注解分类:
    自定义注解
    内置注解:jdk自带的注解



自定义注解:使用@interface

自定义注解案例
package com.leeue.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.annotation.Resources;
import javax.lang.model.element.Element;

/**
 * 
 * @classDesc: 功能描述:(实现自定义注解)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月26日 上午11:03:00
 */
//这个注解 表示这个注解能在哪些地方可以使用这个注解  权限
@Target(value = {ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
//这个注解表示注解的生命周期  这里设置的是运行状态都有效
@Retention(RetentionPolicy.RUNTIME)
@interface TestAnnotation{

    int beanId() default 0; //可以不传参数默认为0
    String className() default ""; //可以不传
    String[] arrArry();//必须要传
}
@TestAnnotation(beanId=1,className="com.leeue.annotation",arrArry= {"11","22"})
public class AnnotationDemo01 {
    private String name;
    public void add() {

    }
}

二、使用自定义注解完成ORM框架

package com.leeue.annotation.demo;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT;
/**
 * 
 * @classDesc: 功能描述:(自定义的Table注解)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月26日 上午11:34:09
 */
@Target(value= {ElementType.TYPE})//这个是权限,表名只能在类上面使用
@Retention(RetentionPolicy.RUNTIME)//标注上在什么时候运行   这个一定要写,
@interface Table{
    String value() default "";

}

/**
 * 
 * @classDesc: 功能描述:(自定义属性注解)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月26日 上午11:35:17
 */
@Target(value= {ElementType.FIELD})//只能在属性上用
@Retention(RetentionPolicy.RUNTIME)
@interface Property{
    String name();
    int length() default 0;
}
/**
 * 
 * @classDesc: 功能描述:(使用自定义注解 实现简单的ORM框架   就是使用java反射+sql拼接)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月26日 上午11:32:15
 */
@Table(value="student")
public class AnnotationDemo02 {
    @Property(name="student_id",length=10)
    private String id;
    @Property(name="student_name",length=10)
    private String name;
    @Property(name="class_name")
    private String className;


    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> forName = Class.forName("com.leeue.annotation.demo.AnnotationDemo02");
        //获取类上面的注解
        Table declaredAnnotation = forName.getDeclaredAnnotation(Table.class);
        //获取类里面的所有的属性
        Field[] declaredFields = forName.getDeclaredFields();
        StringBuffer sBuffer = new StringBuffer();
        sBuffer.append("SELECT ");
        for(int i = 0; i < declaredFields.length; i++) {
            Field field = declaredFields[i];
            Property property = field.getDeclaredAnnotation(Property.class);
            String name = property.name();
            sBuffer.append(name);
            if(i<declaredFields.length-1) {
                sBuffer.append(", ");
            }
        }
        String tableName = declaredAnnotation.value();
        sBuffer.append(" FROM "+tableName);
        System.out.println(sBuffer.toString());

    }
}

三、设计模式

设计模式主要的作用:重复利用、代码易与扩展、提高阅读、减少代码。

设计模式有23种。

分为三类:
创建型:
    工厂、单例
结构型:
    代理、适配器
行为型:
    策略模式



设计模式六大原则:
    开闭原则:扩展性,易于修改。
    里氏代换原则--面向对象
    依赖倒转原则--面向接口编程
    接口隔离原则--接口分离
    迪米特法则--定义类尽量和其他类发生关系
    合成复用原则---代码复用

四、单例设计模式

什么是单例?
    保证jvm中只能有一个实例。
    懒汉式、饿汉式:

    区别:
        懒汉式:线程不安全是需要的时候才会创建。
        饿汉式:线程天生安全,jvm class加载的时候就会初始化

懒汉式:线程不安全,解决方案如下

package com.leeue.design;

/**
 * 
 * @classDesc: 功能描述:(单例模式)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月26日 下午1:43:23
 */
// 包证在JVM中只能有一个实例  线程不安全  要加上synchronized方法 加锁包保证安全 效率低

class Singleto {
    //懒汉式只有需要的时候才会返回
    static private Singleto singleto;
    private Singleto() {

    }
    //方法返回 保证只有一个实例
    static public  Singleto getSingleto() {
        if(singleto == null) {//第一层上锁
            synchronized (Singleto.class) {
                if (singleto == null) {//第二层上锁  双重检验锁
                    singleto = new Singleto();
                }

            }

        }
        return singleto;
    }
}

public class SingletonDemo {
    public static void main(String[] args) {
        Singleto s1 = Singleto.getSingleto();
        Singleto s2 = Singleto.getSingleto();

        System.out.println(s1 == s2);//true
    }
}

饿汉式:线程天生安全

package com.leeue.design;

/**
 * 
 * @classDesc: 功能描述:(单例模式)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月26日 下午1:43:23
 */
// 饿汉模式  天生线程安全

class  SingletonDemo{

    static private SingletonDemo singleto = new SingletonDemo();
    public SingletonDemo() {
        // TODO Auto-generated constructor stub
    }
    static public SingletonDemo getSingletonDemo() {
        return singleto;
    }
}

public class SingletonDemo02 {
    public static void main(String[] args) {
        SingletonDemo s1 = SingletonDemo.getSingletonDemo();
        SingletonDemo s2 = SingletonDemo.getSingletonDemo();

        System.out.println(s1 == s2);//true
    }
}

五:工厂设计模式

简单工厂设计模式
package com.leeue.design.factory;

/**
 * 
 * @classDesc: 功能描述:(简单工厂模式)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月26日 下午2:26:07
 */

interface Car {
    void run();
}

class Aodi implements Car {
    @Override
    public void run() {
        System.out.println("我是奥迪汽车");
    }
}
class BenChi implements Car{
    @Override
    public void run() {
        System.out.println("我是奔驰汽车");
    }
}
class CarFatory {

    public static Car createCar(String name) {

        Car car =null;
        switch (name) {
        case "奥迪":
            car = new Aodi();
            break;
        case "奔驰":
            car = new BenChi();
            break;
        default:
            break;
        }
        return car;
    }
}

public class FactoryDemo01 {
    public static void main(String[] args) {
        Car car = CarFatory.createCar("奥迪");
        car.run();
        Car car2 = CarFatory.createCar("奔驰");
        car2.run();
    }
}

工厂方法
package com.leeue.design.factory;

import org.omg.CORBA.PUBLIC_MEMBER;

/**
 * 
 * @classDesc: 功能描述:(简单工厂模式)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月26日 下午2:26:07
 */

interface Car {
    void run();
}

class Aodi implements Car {
    @Override
    public void run() {
        System.out.println("我是奥迪汽车");
    }
}
class BenChi implements Car{
    @Override
    public void run() {
        System.out.println("我是奔驰汽车");
    }
}
class CarFatory {

    public static Car createCar(String name) {

        Car car =null;
        switch (name) {
        case "奥迪":
            car = new Aodi();
            break;
        case "奔驰":
            car = new BenChi();
            break;
        default:
            break;
        }
        return car;
    }
}

//工厂方法
class BenChiFactory{
    public static Car createCar() {
        return new BenChi();
    }
}

class AoDiFactory {
    public static Car createCar() {
        return new Aodi();
    }
}

public class FactoryDemo01 {
    public static void main(String[] args) {
        Car car = CarFatory.createCar("奥迪");
        car.run();
        Car car2 = CarFatory.createCar("奔驰");
        car2.run();
        //下面演示的是工厂方法

        Car car3 = BenChiFactory.createCar();
        car3.run();
        Car car4 = AoDiFactory.createCar();
        car4.run();
    }
}

六、代理模式

什么是代理模式?
    代理模式设计优点:保证真实角色
    远程代理 RMI
    延迟加载
    AOP:日志打印、事务、权限控制

代理分类:
    静态代理:需要生成代理。
    动态代理:不要生成代理
        jdk动态代理
        cglib动态代理

静态代理

缺点:每次都需要生成代理类

案例:买房和中介

package com.leeue.design.agent;

/**
 * 
 * @classDesc: 功能描述:(JDK动态代理)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月27日 上午10:14:05
 */

interface Hose {
    void maifang();
}

class Leeue implements Hose {
    @Override
    public void maifang() {
        System.out.println("我是leeue终于可以买房了");
    }
}

class Proxy implements Hose {
    // 代理对象
    private Leeue leeue;

    public Proxy(Leeue leeue) {
        this.leeue = leeue;
    }

    @Override
    public void maifang() {
        System.out.println("我是中介,买房交给我了");
        leeue.maifang();
        System.out.println("我是中介,买房结束了");
    }
}

public class StaticAgent {
    public static void main(String[] args) {
        Hose hose = new Proxy(new Leeue());
        hose.maifang();

    }
}

jdk动态代理类

package com.leeue.design.agent;
/**
 * 
 * @classDesc: 功能描述:(jdk 动态代理)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月27日 上午10:25:01
 */

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

class JdkProxy implements InvocationHandler {

    private Object tarjet;


     public JdkProxy(Object tarjet) {
        this.tarjet = tarjet;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("我是中介,买房交给我了");
        Object invoke = method.invoke(tarjet, args);//需要传这个代理类
        System.out.println("我是中介,买房结束了");
        return invoke;
    }

}

public class JdkDynamicAgent {
    public static void main(String[] args) {
        Leeue leeue = new Leeue();
        JdkProxy jdkProxy = new JdkProxy(leeue);
        Hose hose = (Hose) Proxy.newProxyInstance(leeue.getClass().getClassLoader(), leeue.getClass().getInterfaces(), jdkProxy);

        hose.maifang();
    }
}


cglib动态代理 使用框架了

package com.leeue.design.agent;
/**
 * 
 * @classDesc: 功能描述:(cglib 使用第三方框架来完成的的)
 * @author:<a href="[email protected]">李月</a>
 * @Version:v1.0
 * @createTime:2018年7月27日 上午10:42:16
 */

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
//cglib 动态代理
class Cglib implements MethodInterceptor {
    @Override
    public Object intercept(Object oj, Method method, Object[] arrays, MethodProxy methodProxy) throws Throwable {
        System.out.println("我是中介,你买房交给我吧");
        Object invoke = methodProxy.invokeSuper(oj, arrays);
        System.out.println("我是中介买房结束了");
        return invoke;
    }
}

public class CglibAgent {
    public static void main(String[] args) {
        Leeue leeue = new Leeue();

        Cglib cglib = new Cglib();

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Leeue.class);
         enhancer.setCallback(cglib);
         Hose hose = (Hose) enhancer.create();

         hose.maifang();
    }
}

猜你喜欢

转载自blog.csdn.net/leeue/article/details/81215904