java study notes: Design Patterns

First, an overview of design patterns and classification

    1, an overview of design patterns
        Design patterns (Design pattern) is set to be repeated use, known to most people, after cataloging, code design experience summary.
        Use design patterns to reusable code, make the code more easily understood by others, as well as to ensure the reliability of the code structure of the code clearer.
   2, pattern classification designed
        to create a schema (create an object): Singleton pattern, abstract factory pattern, the builder pattern, factory pattern, prototype model.
        Type of model (Object Functions): adapter mode, bridge mode, decorative patterns, combined mode, the appearance model, Flyweight, proxy mode.
        Structural model (composed of objects): template method pattern, command mode, the iterator pattern, observer pattern, intermediary model, the memo mode, the interpreter pattern, state pattern, strategy pattern, duty chain, visitor pattern.

Second, the simple factory pattern overview and use

    1. Overview: also known as static factory method pattern that defines a concrete factory class is responsible for creating instances of some class.
    2, the advantages: The advantage of using a static factory pattern is to achieve the division of responsibility, the core of the model is factory class, factory class contains the necessary selection logic, examples of which can decide when a product is created, and the client is removed from direct Creating product liability, but only consumer products. That static factory pattern without changing the client code can dynamically add products. It defined the responsibilities of the class.
    3, Disadvantages: This static factory class is responsible for creating all objects, if there is to add new objects, or different ways to create some objects, you need to constantly modify the factory class, is not conducive to maintenance of late.

       
Third, using the factory method, and an overview mode

  1. Overview: Factory Method pattern abstract factory class is responsible for defining the interface to create objects, create job specific object is achieved by a concrete class inherit the abstract factory.
  2, the advantages: The client does not need to be responsible for creating an object, which defined the responsibilities of each class, if there is to add new objects, only need to add a specific class and the concrete factory class can not affect the existing code , post-maintenance easier, enhances system scalability
  3, disadvantages: the need for additional coding, increasing the workload
  4, case presentations
    

Fourth, the singleton

   1, Category: lazy and starving the formula Formula
   2, and Formula starving distinction lazy formula

单例模式之饿汉式
public class Student {
    private static Student student=new Student();
    //1.私有化构造
    private Student() {
    }
    //2.提供一个公共的静态方法,让外界通过这个方法,来获取一个该类的对象
    public static Student getStudent(){
        return student;
    }
}
测试类
public class MyTest {
    public static void main(String[] args) {
        Student student = Student.getStudent();
        Student student1 = Student.getStudent();
        System.out.println(student==student1);
    }
}
单例模式之懒汉式
public class Teacher {
    private static Teacher teacher=null;
    //1.私有化构造
    private Teacher() {
    }
    //2.提供公共的静态方法,让外界获取该类的一个对象
    //t1 t2
    public synchronized static Teacher getTeacher(){
        if(teacher==null){
            teacher=new Teacher();
        }
        return teacher;
    }
}
测试类
public class Test {
    public static void main(String[] args) {
        //懒汉式:体现的是一种延迟加载,当需要用的时候,我再帮你去创建这个对象
        //实际开发中 常用饿汉式
        Teacher teacher = Teacher.getTeacher();
        Teacher teacher1 = Teacher.getTeacher();
        System.out.println(teacher==teacher1);
    }
}

3 two ideas, singletons:
             A: Thought thread safety
             b: loading delay thought
4, singleton class Java code embodied Runtime

   A, overview of the Runtime class: Each application has a Java Runtime class instance of the application to the environment is connected with its operators. You can get the current runtime objects by getRuntime method. The application can not create its own instance of class Runtime. 
   b, case presentations: public Process exec (String command) // Dos command execution

public class Demo {
    public static void main(String[] args) throws IOException {
        //这个类,采用的是单例模式之饿汉式
        Runtime runtime = Runtime.getRuntime();
        //Process exec (String command)
        //在单独的进程中执行指定的字符串命令。
        //runtime.exec("calc");//打开计算机
        //runtime.exec("mspaint");//打开画图
        //runtime.exec("notepad");//打开记事本
        //定时关机
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    runtime.exec("shutdown -s -t 0");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, 1000 * 60 * 1);
    }
}

Fifth, use templates and design patterns Overview

    1 Overview: Template Method pattern is to define a skeletal algorithms, and the specific algorithmic delay to subclasses to achieve    
    2, Requirements: time calculation for loop execution 
    three advantages: a stencil method mode, in the definition of the algorithm backbone at the same time, it can be very flexible to achieve specific algorithm to meet the needs of the user flexible   
    4 disadvantage: if the algorithm has modified the skeleton, then you need to modify the abstract class    
    5, case presentations: use template design patterns

public abstract class CalcTime {
    public long testTime() throws IOException {
        long start = System.currentTimeMillis();
        testTimer();
        long end = System.currentTimeMillis();
        return  end-start;
    }
    public abstract void testTimer() throws IOException;
}
public class TestFor extends CalcTime{
    @Override
    public void testTimer() {
        for (int i = 0; i < 1000; i++) {
                   System.out.println(i);
                }
    }
}
public class MyTest {
    public static void main(String[] args) throws IOException {
        CalcTime testFor = new TestFor();
        long l = testFor.testTime();
        System.out.println("耗时" + l + "毫秒");
    }
}

 

Sixth, the use of decorative patterns and overview

   1 Overview: decorative pattern is used by the instance of a subclass of the decoration, the client instance of this subclass to the decorative end. Inherited alternative
   two advantages: the use of decorative patterns, can provide more flexible than the extended objects inherit functionality, which can dynamically add object function, and these functions can be freely combined.
   3, Cons: Just because you can freely mix, so it may appear unreasonable logic.

Seven observer mode and use Overview

 1: Case: find a headhunter to find a job
 2: Subscribers observer = + Publisher
         job seekers search class (registration method, cancellation method, the distribution method)

public class HeaderHunt { //猎头
    //定义两个集合,来装求职者,和工作岗位
    private ArrayList<Worker> mans=new ArrayList<>();
    private ArrayList<Job> jobs = new ArrayList<>();
    //提供注册的方法
    public void addMan(Worker man){
        mans.add(man);
    }
    //提供注销的方法
    public void removeMan(Worker man){
        mans.remove(man);
    }
    //添加岗位
    public void addJob(Job job){
        jobs.add(job);
        //岗位一旦有了之后,我就得通知每一个求职着
        noticeToMan(job);
    }
    //通知的方法
    private void noticeToMan(Job job) {
        for (Worker man : mans) {
            System.out.println(man.getName()+"你好! 有一份"+job.getName()+"月薪"+job.getMoney()+"诚邀你前去面试");
        }
    }
}
public class Job {
    private String name;
    private double money;

    public Job() {
    }

    public Job(String name, double money) {
        this.name = name;
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}
public class Worker {
    private String name;

    public Worker() {
    }

    public Worker(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
测试类
public class Test {
    public static void main(String[] args) {
        Worker man1 = new Worker("张三");
        Worker man2 = new Worker("李四");
        Worker man3 = new Worker("王五");
        Worker man4 = new Worker("赵六");
        //把每个人的信息注册到猎头那里
        HeaderHunt headerHunt = new HeaderHunt();
        headerHunt.addMan(man1);
        headerHunt.addMan(man2);
        headerHunt.addMan(man3);
        headerHunt.addMan(man4);
        //猎头一旦工作岗位更新后 ,就会通知每一个求职者
        headerHunt.addJob(new Job("软件开发工程师",25000));
        headerHunt.removeMan(man3); //移除求职着
        System.out.println("----------------------------");
        headerHunt.addJob(new Job("大数据工程师", 35000));
    }
}

 

Published 24 original articles · won praise 11 · views 2047

Guess you like

Origin blog.csdn.net/weixin_43791069/article/details/86697191