【设计模式】结构型

1,享元模式

对常用数据进行缓存,减轻系统频繁创建的压力,jdk中Integer是很好的例子,如下是对Integer的模仿

class MyInteger {
    private int value;
    private static MyInteger[] cache = new MyInteger[256];

    static {
        for (int i = 0; i < 256; i++) {
            cache[i] = new MyInteger(i - 127);
        }
    }

    public MyInteger(int i) {
        this.value = i;
    }

    //享元模式+构造者模式
    public static MyInteger valueOf(int i) {
        if (i >= -127 && i <= 128) {
            return cache[i + 127];
        }
        return new MyInteger(i);
    }

    @Override
    public String toString() {
        return "MyInteger{" +
                "value=" + value +
                '}';
    }
}

2,代理模式

代理模式是多个框架基础,即通过中间代理,实现面向切面编程(AOP);代理模式有动态与静态之分,静态代理写法固定,这儿着重讲下动态代理(jdk动态代理和cjlib动态代理);

jdk动态代理如下,通过Proxy.newProxyInstance函数返回代理对象,传入类加载器、类实现的接口、invocationHandler;invocationHandler是一个接口,需重写invoke方法,达到aop目的;

/***
 * JDK动态代理的方式,利用接口实现代理
 *
 * ***/
public class ProxyFactory implements InvocationHandler {
    private Object target;

    private Object getProxyInstance(Object target) {
        this.target = target;
        Object instance = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
        return instance;
    }

    public static  T getProxyInstance(Class clazz) {
        try {
            T t = clazz.newInstance();
            ProxyFactory factory = new ProxyFactory();
            Object instance = factory.getProxyInstance(t);
            return (T) instance;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object object = method.invoke(this.target, args);
        after();
        return object;
    }

    private void before() {
        System.out.println("before");
    }

    private void after() {
        System.out.println("after");
    }

    //test
    public static void main(String[] args) {
        User instance = ProxyFactory.getProxyInstance(UserVo.class);
        instance.walk();
    }
}

cglib动态代理利用类继承机制,具体过程如下


public class CglibProxy implements MethodInterceptor {

    public Object getProxyInstance(Class clazz) throws Exception {
        Enhancer enhancer = new Enhancer();
        //设置成父类
        enhancer.setSuperclass(clazz);
        //传入MethodInterceptor,实现aop
        enhancer.setCallback(this);

        return enhancer.create();

    }

    public  T getProxyInstance(T t) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(t.getClass());
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        before();
        Object obj = methodProxy.invokeSuper(o, objects);
        after();
        return obj;
    }


    private void before() {
        System.out.println("before");
    }

    private void after() {
        System.out.println("after");
    }

    //test
    public static void main(String[] args) throws Exception {
        CglibProxy cglibProxy = new CglibProxy();
        User user = new User();
        User proxyInstance = cglibProxy.getProxyInstance(user);
        proxyInstance.walk();
    }
}

3,桥接模式


/**
 * @program: algorithm_by_java
 * @author: 一树
 * @data: 2020/12/1 15:11
 */
public class Client {
    public static void main(String[] args) {
        //创建一个具体角色
        ConcreteImplementorA implementorA = new ConcreteImplementorA();
        //创建一个抽象角色,聚合实现
        RefineAbstraction abs = new RefineAbstraction(implementorA);
        //执行操作
        abs.operation();
    }

    //抽象
    static abstract class Abstraction{
        protected Implementor implementor;

        public Abstraction(Implementor implementor) {
            this.implementor = implementor;
        }

        public void operation(){
            this.implementor.operationImpl();
        }
    }

    //修正抽象
    static class RefineAbstraction extends Abstraction{

        public RefineAbstraction(Implementor implementor) {
            super(implementor);
        }

        @Override
        public void operation() {
            super.operation();
            System.out.println("refined operation");
        }
    }


    //抽象实现
    interface Implementor{
        void operationImpl();
    }

    //具体实现
    static class ConcreteImplementorA implements Implementor{

        @Override
        public void operationImpl() {
            System.out.println("I am ConcreteImplementorA");
        }
    }

    static class ConcreteImplementorB implements Implementor{

        @Override
        public void operationImpl() {
            System.out.println("I am ConcreteImplementorB");
        }
    }
}

4,组合模式

//类似古代三省六部制度,各组合职责分明,而非继承皇室,臃肿
public class Client {
    public static void main(String[] args) {
        System.out.println("============透明组合模式============");
        Course javaBase = new Course("Java入门课程",8280);
        Course ai = new Course("人工智能", 1500);

        CoursePackage coursePackage = new CoursePackage("Java架构师课程", 2);

        Course design = new Course("Java设计模式", 1500);
        Course source = new Course("源码分析", 1500);
        Course softKill = new Course("软技能", 1500);

        coursePackage.addChild(design);
        coursePackage.addChild(source);
        coursePackage.addChild(softKill);

        CoursePackage catalog = new CoursePackage("课程主目录",1);
        catalog.addChild(javaBase);
        catalog.addChild(ai);
        catalog.addChild(coursePackage);

        catalog.print();
    }
}

abstract class CourseComponent {

    //定义共有操作:不使用接口是因为子类必须实现接口方法(不考虑default)
    public void addChild(CourseComponent component) {
        throw new UnsupportedOperationException("unsupported addChild");
    }

    public void removeChild(CourseComponent component) {
        throw new UnsupportedOperationException("unsupported removeChild");
    }

    public String getName(CourseComponent component) {
        throw new UnsupportedOperationException("unsupported getName");
    }

    public double gerPrice(CourseComponent catalogComponent) {
        throw new UnsupportedOperationException("unsupported gerPrice");
    }

    public void print() {
        throw new UnsupportedOperationException("unsupported print");
    }
}

//A实现
class Course extends CourseComponent {
    private String name;
    private double price;

    public Course(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String getName(CourseComponent component) {
        return this.name;
    }

    @Override
    public double gerPrice(CourseComponent catalogComponent) {
        return this.price;
    }


    @Override
    public void print() {
        System.out.println(name + "(" + price + "元)");
    }
}

//B实现
class CoursePackage extends CourseComponent {
    private List items = new ArrayList<>();
    private String name;
    private Integer level;

    public CoursePackage(String name, Integer level) {
        this.name = name;
        this.level = level;
    }

    @Override
    public String getName(CourseComponent component) {
        return this.name;
    }

    @Override
    public void addChild(CourseComponent component) {
        items.add(component);
    }

    @Override
    public void removeChild(CourseComponent component) {
        items.remove(component);
    }

    @Override
    public void print() {
        System.out.println(this.name);

        for (CourseComponent item : items) {
            if (this.level != null) {
                for (int i = 0; i < this.level; i++) {
                    //打印level级目录
                    System.out.print("  ");
                }

                for (int i = 0; i < this.level; i++) {
                    if (i == 0) {
                        System.out.print("+");
                    }
                    System.out.print("-");
                }

            }
            item.print();
        }
    }
}

5,装饰者模式


/**
 * @program: suanfa_by_java
 * @author: 一树
 * @data: 2020/11/1 16:48
 */


/*抽象煎饼类*/
public abstract class BatterCake {
    protected abstract String getMsg();

    protected abstract int getPrice();
}

/*基类*/
class BaseBatterCake extends BatterCake {

    @Override
    protected String getMsg() {
        return "煎饼";
    }

    @Override
    protected int getPrice() {
        return 5;
    }
}


/*扩展套餐的抽象装饰类BatterCakeDecorator*/

abstract class BatterCakeDecorator extends BatterCake {
    //静态代理,委派
    private BatterCake batterCake;

    public BatterCakeDecorator(BatterCake batterCake) {
        this.batterCake = batterCake;
    }

    protected abstract void doSomething();

    @Override
    protected int getPrice() {
        return this.batterCake.getPrice();
    }

    @Override
    protected String getMsg() {
        return this.batterCake.getMsg();
    }
}

/*创建鸡蛋装饰者*/

class EggDecorator extends BatterCakeDecorator {


    public EggDecorator(BatterCake batterCake) {
        super(batterCake);
    }

    @Override
    protected void doSomething() {

    }


    @Override
    protected String getMsg() {
        return super.getMsg() + " +1鸡蛋";
    }

    @Override
    protected int getPrice() {
        return super.getPrice() + 1;
    }
}

/*创建香肠装饰者*/

class SausageDecorator extends BatterCakeDecorator {


    public SausageDecorator(BatterCake batterCake) {
        super(batterCake);
    }

    @Override
    protected void doSomething() {

    }


    @Override
    protected String getMsg() {
        return super.getMsg() + " +1香肠";
    }

    @Override
    protected int getPrice() {
        return super.getPrice() + 2;
    }
}

class Test{

    public static void main(String[] args) {
        //路边买了一个煎饼
        BatterCake batterCake = new BaseBatterCake();
        //加一个鸡蛋
        batterCake = new EggDecorator(batterCake);
        //再加一个鸡蛋
        batterCake = new EggDecorator(batterCake);
        //再加一个香肠
        batterCake = new SausageDecorator(batterCake);

        System.out.println("batterCake.getMsg() = " + batterCake.getMsg());
        System.out.println("batterCake.getPrice() = " + batterCake.getPrice());
    }
}

6,适配器模式


interface DC5{
    int outputDC5();
}

class AC220 {
    public int outputAC220V(){
        int output = 220;
        System.out.println("输出电压:"+output+"v");
        return output;
    }
}

public class PowerAdapter implements DC5{

    private AC220 ac220;

    public PowerAdapter(AC220 ac220) {
        this.ac220 = ac220;
    }

    @Override
    public int outputDC5() {
        int adapterInput = ac220.outputAC220V();
        //变压器...
        int adapterOutput = adapterInput/44;
        System.out.println("输出电压:"+adapterOutput+"v");
        return adapterOutput;
    }

    public static void main(String[] args) {
        DC5 dc5 = new PowerAdapter(new AC220());
        System.out.println(dc5.outputDC5());
    }
}

7,门面模式

暴露可用api,隐藏不可用api

//隐藏复杂实现,对外提供稳定API
public class Client {
}

你可能感兴趣的:(蓝桥杯,java,职场和发展)