优秀的代码设计

常用设计模式

工厂方法

定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。

public class FactoryDemo {
    interface IProduct {
        public void productMethod();
    }

    static class Product implements IProduct {
        public void productMethod() {
            System.out.println("产品");
        }
    }

    interface IFactory {
        IProduct createProduct();
    }

    static class Factory implements IFactory {
        public IProduct createProduct() {
            return new Product();
        }
    }

    public static void main(String[] args) {
        IFactory factory = new Factory();
        IProduct prodect = factory.createProduct();
        prodect.productMethod();
    }
}

抽象工厂

定义:为创建一组相关或相互依赖的对象提供一个接口,而且无需指定他们的具体类。

public class FactoryDemo {
    interface IProduct1 {
        void show();
    }

    interface IProduct2 {
        void show();
    }

    static class Product1 implements IProduct1 {
        public void show() {
            System.out.println("这是1型产品");
        }
    }

    static class Product2 implements IProduct2 {
        public void show() {
            System.out.println("这是2型产品");
        }
    }

    interface IFactory {
        IProduct1 createProduct1();

        IProduct2 createProduct2();
    }

    static class Factory implements IFactory {
        public IProduct1 createProduct1() {
            return new Product1();
        }

        public IProduct2 createProduct2() {
            return new Product2();
        }
    }

    public static void main(String[] args) {
        IFactory factory = new Factory();
        factory.createProduct1().show();
        factory.createProduct2().show();
    }
}

输出:

优秀的代码设计_第1张图片
Paste_Image.png

策略模式

定义:定义一组算法,将每个算法都封装起来,并且使他们之间可以互换。即面向接口编程。

public class Client {

    interface IStrategy {
        void doSomething();
    }

    static class ConcreteStrategy1 implements IStrategy {
        public void doSomething() {
            System.out.println("具体策略1");
        }
    }

    static class ConcreteStrategy2 implements IStrategy {
        public void doSomething() {
            System.out.println("具体策略2");
        }
    }

    static class Context {
        private IStrategy strategy;

        public Context(IStrategy strategy) {
            this.strategy = strategy;
        }

        public void execute() {
            strategy.doSomething();
        }
    }

    public static void main(String[] args) {
        Context context;
        System.out.println("-----执行策略1-----");
        context = new Context(new ConcreteStrategy1());
        context.execute();

        System.out.println("-----执行策略2-----");
        context = new Context(new ConcreteStrategy2());
        context.execute();
    }
}

输出:

优秀的代码设计_第2张图片
Paste_Image.png

装饰者

public class DecoratDemo {
    interface Work {
        void work();
    }

    static class Son implements Work {        //所有装饰类都实现一个统一的接口或者继承同一个父类
        @Override
        public void work() {
            System.out.println("画画...");
        }
    }


    static class Mother implements Work {
        Work worker;                   //需要被增强的类内部维护一个需要“继承”的类实例,但不使用继承

        public Mother(Work worker) {
            this.worker = worker;
        }

        @Override
        public void work() {
            worker.work();             //调用的哪个work方法?
            System.out.println("给画上颜色..");
        }
    }

    static class Father implements Work {
        //需要被增强的类的引用
        Work worker;

        public Father(Work worker) {
            this.worker = worker;
        }

        @Override
        public void work() {
            worker.work();
            System.out.println("上画框...");
        }

    }

    public static void main(String[] args) {
        Son s = new Son();
        s.work();
        Mother m = new Mother(s);            //将Son对象实例作为参数传递进去,从而实现类似“继承”的功能
        m.work();
        Father f = new Father(m);            //将Mother对象实例传入,Father对象实现三个功能
        f.work();                            //如果将上一行替换成 Father f = new Father(s); 将出现什么样的输出?
    }
}

输出:

优秀的代码设计_第3张图片
Paste_Image.png

代理模式

静态代理:

public class ProxyDemo {
    interface Subject {
        void request();
    }

    private static class RealSubject implements Subject {
        public void request() {
            System.out.println("request");
        }
    }

    private static class Proxy implements Subject {
        private Subject subject;

        public Proxy(Subject subject) {
            this.subject = subject;
        }

        public void request() {
            System.out.println("PreProcess");
            subject.request();
            System.out.println("PostProcess");
        }
    }

        public static void main(String args[]) {
            RealSubject subject = new RealSubject();
            Proxy p = new Proxy(subject);
            p.request();
        }
}

动态代理:


public class DynamicProxyDemo {
    /**
     * 接口
     */
    interface Subject {
        void request();
    }

    /**
     * 委托类
     */
    private static class RealSubject implements Subject {
        public void request() {
            System.out.println("request");
        }
    }

    /**
     * 代理类的调用处理器
     */
    private static class ProxyHandler implements InvocationHandler {
        private Subject subject;

        public ProxyHandler(Subject subject) {
            this.subject = subject;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            System.out.println("PreProcess");//定义预处理的工作,当然你也可以根据 method 的不同进行不同的预处理工作
            Object result = method.invoke(subject, args);
            System.out.println("PostProcess");
            return result;
        }
    }

    public static void main(String[] args) {
        RealSubject realSubject = new RealSubject();    //1.创建委托对象
        ProxyHandler handler = new ProxyHandler(realSubject);    //2.创建调用处理器对象
        Subject proxySubject = (Subject) Proxy.newProxyInstance(RealSubject.class.getClassLoader(),
                RealSubject.class.getInterfaces(), handler);    //3.动态生成代理对象
        proxySubject.request();    //4.通过代理对象调用方法
    }
}

输出:

优秀的代码设计_第4张图片
Paste_Image.png

模板方法

定义:定义一个操作中算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变算法的结构即可重定义该算法中的某些特定步骤。

//客户端
public class TempleDemp {

    //AbstractClass(抽象类)
    static abstract class AbstractClass {

        protected abstract void absMethod();

        protected void hookMethod() {
            //base null
        }

        private final void concreteMethod() {
            System.out.println("Base Logic Code!");
        }

        public void templateMethod() {
            absMethod();
            hookMethod();
            concreteMethod();
        }
    }

    //ConcreteClass(具体子类)
    static class ConcreteClass extends AbstractClass {

        @Override
        protected void absMethod() {
            System.out.println("Signal Logic Code!");
        }

        @Override
        protected void hookMethod() {
            super.hookMethod();
            System.out.println("hookMethod Logic Code!");
        }
    }

    public static void main(String[] args) {
        AbstractClass abstractClass = new ConcreteClass();
        abstractClass.templateMethod();
    }
}

输出:

优秀的代码设计_第5张图片
Paste_Image.png

适配器模式

public class AdapterDemo {  
    /**
     * 德标接口
     */
    public interface DBSocketInterface {

        /**
         * 这个方法的名字叫做:使用两项圆头的插口供电
         * 本人英语就这个水平
         */
        void powerWithTwoRound();
    }

    /**
     * 德国插座
     */
    public static class DBSocket implements DBSocketInterface {

        public void powerWithTwoRound() {
            System.out.println("使用两项圆头的插孔供电");
        }
    }

    /**
     * 国标接口
     */
    public interface GBSocketInterface {

        /**
         * 这个方法的名字叫做:使用三项扁头的插口供电
         * 本人英语就这个水平,从有道词典查得, flat意思好像是: 扁的
         */
        void powerWithThreeFlat();
    }

    public static class GBSocket implements GBSocketInterface {

        @Override
        public void powerWithThreeFlat() {
            System.out.println("使用三项扁头插孔供电");
        }
    }

    public static class SocketAdapter implements DBSocketInterface {   //实现旧接口

        //组合新接口
        private GBSocketInterface gbSocket;

        /**
         * 在创建适配器对象时,必须传入一个新街口的实现类
         *
         * @param gbSocket
         */
        public SocketAdapter(GBSocketInterface gbSocket) {
            this.gbSocket = gbSocket;
        }


        /**
         * 将对就接口的调用适配到新接口
         */
        @Override
        public void powerWithTwoRound() {
            gbSocket.powerWithThreeFlat();
        }

    }

    /**
     * 德国宾馆
     */
    public static class Hotel {

        //旅馆中有一个德标的插口  
        private DBSocketInterface dbSocket;

        public Hotel(DBSocketInterface dbSocket) {
            this.dbSocket = dbSocket;
        }

        //旅馆中有一个充电的功能  
        public void charge() {

            //使用德标插口充电  
            dbSocket.powerWithTwoRound();
        }
    }

    public static void main(String[] args) {
        GBSocketInterface gbSocket = new GBSocket();
        SocketAdapter socketAdapter = new SocketAdapter(gbSocket);
        Hotel hotel = new Hotel(socketAdapter);
        hotel.charge();
    }
}

输出:

Paste_Image.png

建造者

定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

public class BuilderDemo {
    private static class Product {
        private String name;
        private String type;

        public void showProduct() {
            System.out.println("名称:" + name);
            System.out.println("型号:" + type);
        }

        static class Builder {
            private String name;
            private String type;

            private Builder setName(String name) {
                this.name = name;
                return this;
            }

            private Builder setType(String type) {
                this.type = type;
                return this;
            }

            public Product build() {
                Product product = new Product();
                product.name = name;
                product.type = type;
                return product;
            }
        }
    }

    public static class Director {
        private Product.Builder builder = new Product.Builder();

        public Product getAProduct() {
            builder.setName("宝马汽车");
            builder.setType("X7");
            return builder.build();
        }

        public Product getBProduct() {
            builder.setName("奥迪汽车");
            builder.setType("Q5");
            return builder.build();
        }
    }


    public static void main(String[] args) {
        Director director = new Director();
        Product product1 = director.getAProduct();
        product1.showProduct();

        Product product2 = director.getBProduct();
        product2.showProduct();
    }
}

输出:

优秀的代码设计_第6张图片
Paste_Image.png

观察者

定义:定义对象间一种一对多的依赖关系,使得当每一个对象改变状态,则所有依赖于它的对象都会得到通知并自动更新。

public class ObserverDemo {
    private static abstract class Subject {
        private Vector obs = new Vector<>();

        public void addObserver(Observer obs) {
            this.obs.add(obs);
        }

        public void delObserver(Observer obs) {
            this.obs.remove(obs);
        }

        protected void notifyObserver() {
            for (Observer o : obs) {
                o.update();
            }
        }

        public abstract void doSomething();
    }

    private static class ConcreteSubject extends Subject {
        public void doSomething() {
            System.out.println("被观察者事件反生");
            this.notifyObserver();
        }
    }

    interface Observer {
        void update();
    }

    private static class ConcreteObserver1 implements Observer {
        public void update() {
            System.out.println("观察者1收到信息,并进行处理。");
        }
    }

    private static class ConcreteObserver2 implements Observer {
        public void update() {
            System.out.println("观察者2收到信息,并进行处理。");
        }
    }

    
        public static void main(String[] args) {
            Subject sub = new ConcreteSubject();
            sub.addObserver(new ConcreteObserver1()); //添加观察者1
            sub.addObserver(new ConcreteObserver2()); //添加观察者2
            sub.doSomething();
        }
}

输出:

优秀的代码设计_第7张图片
Paste_Image.png

单例模式

定义:确保一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

懒汉模式

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}
    public static synchronized Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
}  
public class Singleton {  
    private volatile static Singleton singleton;  
    private Singleton (){}  
    public static Singleton getSingleton() {  
        if (singleton == null) {  
            synchronized (Singleton.class) {  
                if (singleton == null) {  
                    singleton = new Singleton();  
                }  
            }  
        }  
        return singleton;  
    }  
} 

饿汉模式

public class Singleton {  
    private static Singleton instance = new Singleton(); 
    private Singleton (){}
    public static Singleton getInstance() {  
        return instance;  
    }  
}  

迭代器模式

定义:提供一种方法访问一个容器对象中各个元素,而又不暴露该对象的内部细节。

public class IteratorDemo {

    interface Iterator {
        T next();

        boolean hasNext();
    }

    private static class ConcreteIterator implements Iterator {
        private List list = null;
        private int cursor = 0;

        public ConcreteIterator(List list) {
            this.list = list;
        }

        public boolean hasNext() {
            if (cursor == list.size()) {
                return false;
            }
            return true;
        }

        public T next() {
            T obj = null;
            if (this.hasNext()) {
                obj = this.list.get(cursor++);
            }
            return obj;
        }
    }

    interface Aggregate {
        void add(T obj);

        void remove(T obj);

        Iterator iterator();
    }

    static class ConcreteAggregate implements Aggregate {
        private List list = new ArrayList<>();

        public void add(String obj) {
            list.add(obj);
        }

        public Iterator iterator() {
            return new ConcreteIterator<>(list);
        }

        public void remove(String obj) {
            list.remove(obj);
        }
    }

    public static void main(String[] args) {
        Aggregate ag = new ConcreteAggregate();
        ag.add("小明");
        ag.add("小红");
        ag.add("小刚");
        Iterator it = ag.iterator();
        while (it.hasNext()) {
            String str = (String) it.next();
            System.out.println(str);
        }
    }
}

优秀的代码设计

慢慢更~

你可能感兴趣的:(优秀的代码设计)