Share five design patterns

Share on five design patterns

Design mode is accumulated in the process of developing a proven and can be used to solve a particular environment, recurring, solutions to specific problems.


Factory Pattern

Divided into simple, general, three specific abstract model, this analysis identifies only simple and general plant factory.

Features factory method pattern is to define an interface for creating an object, but let subclasses decide which specific instance of the class. The method of making a factory to instantiate the class to delay its subclasses.

Usage scenarios : when you need to create complex objects, suitable for a database, log system. Simple to be able to easily use the new objects with no need to use the factory pattern.

Advantages : In addition to the direct dependencies between consumers and entities, and can be "processing" of objects created in the case of consumer non-inductive.

Drawbacks : increasing the amount of code in a way so that the project becomes bloated.

public interface Clothes {
    /**
     * 制造衣物
     */
    void make();
}
/**
 * 裙子
 */
class Dress implements Clothes {
    @Override
    public void make() {
        System.out.println("给你裙子");
    }
}
/**
 * 衬衫
 */
class Shirt implements Clothes {
    @Override
    public void make() {
        System.out.println("给你衬衫");
    }
}
/**
 * 裤子
 */
class Pants implements Clothes {
    @Override
    public void make() {
        System.out.println("给你裤子");
    }
}
/**
 * 没造出来
 */
class NoClothes implements Clothes {
    @Override
    public void make() {
        System.out.println("没造出来");
    }
}
  1. Simple Factory:

    Class specific functions need to implement the same interface , the factory is responsible for logical decision and instantiated .

    Consumers do not care about the internal operation of the plant, made only demand , instantiated by factory processing, and returns in line with corresponding instances of consumer needs.

    class SimpleFactory {
        Clothes makeClothes(String type) {
            Clothes clothes;
            switch (type) {
                case "dress":
                    clothes = new Dress();
                    break;
                case "shirt":
                    clothes = new Shirt();
                    break;
                case "pants":
                    clothes = new Pants();
                    break;
                default:
                    clothes = new NoClothes();
                    break;
            }
            return clothes;
        }
    }
    
    public class SimpleFactoryDemo {
        public static void main(String[] args) {
            Clothes clothes;
            System.out.println("简单工厂模式:");
            SimpleFactory simpleFactory = new SimpleFactory();
    
            System.out.println("工厂,我需要裤子");
            clothes = simpleFactory.makeClothes("pants");
            clothes.make();
    
            System.out.println("工厂,我需要衬衫");
            clothes = simpleFactory.makeClothes("shirt");
            clothes.make();
        }
    }

    Advantage of consumers and easy to use, consumers end modification functions only need to change the name of the parameters passed to add features or modify the function: no need to modify the consumer code, simply add the corresponding judgment branch in the factory.

    Drawbacks : When the object to be created and more , the amount of code factory class will be quite high, while the need to modify each factory class maintenance, leading to increased factory class coupling, while a violation of the principle of opening and closing.

  2. Normal Factory:

    In a specific class that implements the same interface functions on the basis of all factory class inherit the same abstract class configuration . Migrating simple logic to determine the factory to the client, the consumer choose to use the factory, and the factory is responsible for creating the different functions of different specific categories, namely factories and feature class-one correspondence .

    /**
     * 抽象工厂类
     */
    abstract class AbstractFactory {
        /**
         * 抽象获取实体的方法
         *
         * @return 衣物实体
         */
        abstract Clothes getClothes();
    }
    
    /**
     * 衬衫工厂
     */
    class ShirtFactory extends AbstractFactory {
        @Override
        Clothes getClothes() {
            System.out.println("衬衫工厂开工");
            return new Shirt();
        }
    }
    
    /**
     * 裙子工厂
     */
    class DressFactory extends AbstractFactory {
        @Override
        Clothes getClothes() {
            System.out.println("裙子工厂开工");
            return new Dress();
        }
    }
    
    public class NormalFactoryDemo {
        public static void main(String[] args) {
            AbstractFactory factory;
            System.out.println("工厂模式:");
    
            System.out.println("想要裙子,来个裙子工厂造一下");
            factory = new DressFactory();
            factory.getClothes().make();
    
            System.out.println("想要衬衫,来个衬衫工厂造一下");
            factory = new PantsFactory();
            factory.getClothes().make();
        }
    }

    Advantage : reducing the degree of coupling the plant to overcome the shortcomings of the simple opening and closing of the plant in violation of the principle.

    Drawbacks : maintenance or add features, increase the amount of code you need to be modified.

Combined mode

Combined mode is a combination of a plurality of objects in a tree structure to represent "part - whole" hierarchy, so that the consumer can be treated by the process of combining a plurality of individual objects in the object mode .

The most critical areas to achieve the combined mode is interoperable interface .

It has the same base object and an interface between the assembled complex object, which is a combination of the object model can be a combination of a simple object and the matching process reasons.

Usage scenarios : tree menu, tree folder management, etc.

/**
 * 抽象构件
 */
abstract class AbstractComponent {
    String mark;

    AbstractComponent(String mark) {
        this.mark = mark;
    }

    /**
     * 添加子节点
     */
    abstract void add(AbstractComponent component);

    /**
     * 删除子节点
     */
    abstract void remove(AbstractComponent component);

    /**
     * 显示结构
     */
    abstract void function(int depth);
}

/**
 * 构件类型1:分支型
 * 分支型特有:实现添加与删除节点功能
 *    同时实现方法功能
 */
class Branch extends AbstractComponent {

    Branch(String mark) {
        super(mark);
    }

    private List<AbstractComponent> components = new ArrayList<>();

    @Override
    void add(AbstractComponent component) {
        components.add(component);
    }

    @Override
    void remove(AbstractComponent component) {
        components.remove(component);
    }

    @Override
    void function(int depth) {
        for (int i = 1; i < depth; i++) {
            System.out.print("--");
        }
        System.out.println(mark);
        for (AbstractComponent component : components
        ) {
            component.function(depth + 1);
        }
    }
}

/**
 * 构件类型2:末端型
 * 仅实现方法功能
 */
class Extremity extends AbstractComponent {

    Extremity(String mark) {
        super(mark);
    }

    @Override
    void add(AbstractComponent component) {
    }

    @Override
    void remove(AbstractComponent component) {
    }

    @Override
    void function(int depth) {
        for (int i = 1; i < depth; i++) {
            System.out.print("--");
        }
        System.out.println(mark);
    }
}

public class CompositeDemo {
    public static void main(String[] args) {
        System.out.println("设计模式-组合模式Demo:\n");
        //初始化根节点
        AbstractComponent root = new Branch("根节点构件");

        //配置分支
        AbstractComponent branch1 = new Branch("分支构件1");
        branch1.add(new Extremity("末端构件1-1"));

        AbstractComponent branch2 = new Branch("分支构件2");
        AbstractComponent branch21 = new Branch("分支构件2-1");
        branch21.add(new Extremity("末端构件2-1-1"));
        branch2.add(branch21);

        AbstractComponent branch22 = new Branch("分支构件2-2");
        branch22.add(new Extremity("末端构件2-2-1"));
        branch22.add(new Extremity("末端构件2-2-2"));
        branch2.add(branch22);

        //组合构件
        root.add(branch1);
        root.add(branch2);
        root.add(new Branch("分支构件3"));
        root.add(new Extremity("末端构件3"));

        //使用构件
        root.function(1);
    }
}

Advantage:

  1. Combined mode allows consumers consistently processed and object containers , without concern that the processing containers in a single object or target combination.
  2. So that consumers do not directly dependent complex object container, to reduce the degree of coupling .
  3. Can be more easily added to the subject composition new member .

Drawbacks: making the design more complex . Consumers need to spend more time to sort out the hierarchical relationships between classes.

Decorator

Features decorator pattern is allowed to add new functionality to an existing object, without changing its structure .

This pattern creates a decorative, used to wrap the original class , and signed under the premise of maintaining the integrity of the class method provides additional functionality.

Usage scenarios : the old code maintenance, dynamically add functionality to objects

/**
 * 抽象构件,装饰器和基础构件都需要继承它
 */
abstract class AbstractComponent {
    /**
     * 功能
     */
    abstract void function();
}

/**
 * 基础构件
 */
class BaseComponent extends AbstractComponent {

    @Override
    void function() {
        System.out.println("这里是基本类在小声说话");
    }
}

/**
 * 装饰器构件
 */
class Decorator extends AbstractComponent {
    private AbstractComponent component;

    Decorator(AbstractComponent component) {
        this.component = component;
    }

    @Override
    void function() {
        component.function();
        speakLoudly();
    }

    void speakLoudly() {
        System.out.println("然后借助装饰器又喊了一遍");
    }
}

public class DecoratorDemo {
    public static void main(String[] args) {
        AbstractComponent baseComponent = new BaseComponent();
        AbstractComponent superComponent = new Decorator(baseComponent);
      
        System.out.println("基本类:");
        baseComponent.function();
      
        System.out.println("装饰器增强:");
        superComponent.function();
    }
}

Advantages :

  1. Dynamic expansion Functional, flexible than class inheritance, and transparent to consumers.
  2. Can be decorated several times for the same decorated objects , create complex functions behave differently.

Drawbacks :

  1. A multilayer decorative's code is more complicated .
  2. Since each of the decoration layer creates a corresponding object , when the decoration is nested too, it can result in excessive small objects.
  3. Decorative nesting will lead to error-prone, and debugging to troubleshoot high complexity .

Bridge Mode

Bridge mode is an abstraction separated from its implementation , so that they can be independently varied.

Providing a plurality of dimensions for the object change without introducing additional complexity.

Paozhaopaozhe program encountered a bridge, the bridge to go where.

Usage scenarios : the need to have a sufficiently high flexibility of the inter-component system, the switching system object dynamically at runtime, undesirable inherited multi-level system.

/**
 * 被桥接的类应该实现这个接口
 */
interface Bridgeable {
    /**
     * 功能接口
     */
    public void method();
}

/**
 * 跑步模式
 */
class RunningBridge implements Bridgeable {
    @Override
    public void method() {
        System.out.println("连接跑步端口\n一直在跑步...");
    }
}

/**
 * 站定模式
 */
class StandingBridge implements Bridgeable {
    @Override
    public void method() {
        System.out.println("连接原地呆着端口\n站在原地不动...");
    }
}

/**
 * 定义一个抽象类桥,定义桥接目标的抽象实例
 */
abstract class AbstractBridge {

    /**
     * 待放入的桥接目标
     */
    private Bridgeable bridgeable;

    /**
     * 使用桥接目标的方法
     */
    public void method() {
        bridgeable.method();
    }

    /**
     * 设置桥接的目标
     */
    void setBridgeable(Bridgeable bridgeable) {
        this.bridgeable = bridgeable;
    }

    /**
     * 获取桥接的目标
     */
    Bridgeable getBridgeable() {
        return bridgeable;
    }
}

/**
 * 实现功能的桥
 */
class MyBridge extends AbstractBridge {
    @Override
    public void method() {
        getBridgeable().method();
    }
}

public class BridgeDemo {
    public static void main(String[] args) {
        // 实例化一个桥
        AbstractBridge bridge = new MyBridge();

        // 实例化一个桥接目标
        RunningBridge runningBridge = new RunningBridge();
        // 把目标传入桥
        bridge.setBridgeable(runningBridge);
        // 通过桥使用目标
        bridge.method();

        // 实例化一个桥接目标
        StandingBridge standingBridge = new StandingBridge();
        // 把目标传入桥
        bridge.setBridgeable(standingBridge);
        // 通过桥统一的方法进去
        bridge.method();
    }
}

Advantages :

1. 实现了***抽象与实现部分的分离***。
  1. * Improve the function of scalability .
  2. Providing dynamic switching mode.

Drawbacks :

1. 增加了系统的***设计和理解难度***。
  1. For systems in different dimensions requires a clear distinction , therefore be limited.

Proxy mode

Proxy mode is to provide consumers with a proxy object, the proxy object by controlling a reference to the object's implementation.

Acting class implements a functional interface, and create a class that implements the interface specific functions in the construction, consumer proxy class by calling the function interface of the proxy class to call the actual function of the class.

It is very similar to the decorative mode, except that the class object is created in the constructor, and a decorator's class construct passed in the outside.

Usage scenarios : when the need to restrict access, you need to distinguish when dealing with certain methods, certain features need to be extended.

Advantages :

  1. Intermediary isolation, functional objects can be separated from consumers and design, invoked by proxy class.
  2. In line with the principle of opening and closing, no modification has been packaged good specific functional classes.

Drawbacks :

  1. Because between the client and the real object increased the proxy object, so some type of proxy mode may result in slower processing speed requests.
  2. Implementing a proxy mode requires additional work to achieve some agency model is very complex.
/**
 * 代理沟通的接口
 */
interface Proxyable {
    /**
     * 功能
     */
    public void method();
}

/**
 * 实现功能的具体类
 */
class ProxySource implements Proxyable {
    @Override
    public void method() {
        System.out.println("作者出来说话");
    }
}
  1. Static agents

    Create a proxy class, the target object extensions in conformity with the principle of opening and closing.

    /**
     * 静态代理
     */
    class StaticProxy implements Proxyable {
        private ProxySource proxySource = null;
    
        StaticProxy() {
            proxySource = new ProxySource();
        }
    
        @Override
        public void method() {
            System.out.println("代理人收到消息,去找作者");
            proxySource.method();
            System.out.println("代理人的任务做完了");
        }
    }

    Advantages : in line with the principle of opening and closing , and for minimal impact on performance .

    Drawbacks : when the maintenance workload , need to increase the corresponding proxy for each new service. And when the interface changes, also need to modify the proxy class.

  2. Dynamic Proxy

    No need to manually create a proxy class, only need to write dynamic processor. Generated by the proxy object dynamically at runtime reflection.

    /**
     * 动态代理
     */
    class DynamicProxy  {
        /**
         * 配置动态代理调用
         */
        private static final InvocationHandler SOURCE_HANDLE = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = method.invoke(new ProxySource(), args);
                System.out.println("动态代理人的任务做完了");
                return result;
            }
        };
    
        /**
         * 获取被代理的实例
         */
        Proxyable getProxy() {
            Proxyable proxyInstance;
            System.out.println("动态代理人开始到处找作者");
            proxyInstance = (Proxyable) Proxy.newProxyInstance(ProxySource.class.getClassLoader(),
                    new Class[] { Proxyable.class }, SOURCE_HANDLE);
            System.out.println("找到作者了");
            return proxyInstance;
        }
    }

    Advantages :

    1. Dynamic proxies greatly reduces the amount of code development.
    2. It reduces dependence on service interface, reducing the degree of coupling.

    Drawbacks :

    1. Limited to only supported interface agent
    2. Because the reflective mechanism, low operating efficiency

Guess you like

Origin www.cnblogs.com/ZoraZora59/p/11615344.html