[single instance mode, multi instance mode, enumeration, factory mode]

Posted by Slashscape on Sat, 19 Feb 2022 16:37:01 +0100

day15 [single instance mode, multi instance mode, enumeration, factory mode]

Today's goal

  • Singleton mode ----- > must master
    • Hungry Han style single case
    • Lazy single column
  • Multi case mode ----- > must master
  • Enumeration ----- > must master
    • Define enumeration
    • Use enumeration
  • Factory mode ----- > must master
  • lombok plugin

Chapter I single example design mode

1.1 overview of single case design mode

introduce

public class Person{
    
}
public class Test{
    public static void main(String[] args){
        Person p1 = new Person();
        Person p2 = new Person();
        Person p3 = new Person();
        //...
    }
}

The role of singleton design pattern

Singleton mode is a commonly used software design mode. The singleton pattern can ensure that there is only one instance of the class applying the pattern in the system. That is, a class has only one object instance.

Implementation steps of singleton design pattern

  1. Privatize the construction method so that it cannot instantiate the class object outside the class through the new keyword.
  2. Create a unique object inside the class
  3. Define a static method to return this unique object.

Type of example design pattern

According to the time of instantiating the object, the single instance design mode is divided into the following two types:

  1. Starving Han single case design mode
  2. Lazy singleton design pattern

1.2 hungry Han single case design mode

  • Overview: the starving Han singleton design pattern is that the object has been created when using the class. No matter whether the instantiated object will be used in the future, it can be created first. Very anxious, so it is called "hungry man mode".

  • The code is as follows:

    // Hungry Chinese single instance design pattern: the object has been created when using the class. No matter whether the instantiated object will be used in the future, it can be created first.
    // Very anxious, so it is called "hungry man mode".
    

public class Person {
// 1. Privatize the construction method to prevent the creation of objects outside the class by calling the construction method new
private Person(){

  }

  // 2. Create a unique object inside the class
  private static final Person p = new Person();

  // 3. Provide a public static method to obtain the unique object of this class
  public static Person getInstance(){
      return p;
  }
  
  public static void method(){}

}

```java
public class Test {
    public static void main(String[] args) {
       // Person.method();//  A unique object of this class has been created

        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
    }
}

result: Same address value
com.itheima.demo1_Hungry Han single case design mode.Person@4554617c
com.itheima.demo1_Hungry Han single case design mode.Person@4554617c
com.itheima.demo1_Hungry Han single case design mode.Person@4554617c
com.itheima.demo1_Hungry Han single case design mode.Person@4554617c
com.itheima.demo1_Hungry Han single case design mode.Person@4554617c

1.3 lazy single case design mode

  • Overview: the lazy singleton design pattern is that the object is created only when the getInstance() method is called. Don't rush to create the object first, and then create the object when it needs to be used. Don't worry, so it's called "lazy mode".

  • The code is as follows:

    // Lazy singleton design pattern: the object is created only when the getInstance() method is called. Don't rush to create the object first, and then create the object when it needs to be used.
    // Don't worry, so it's called "lazy mode".
    

public class Person {
// 1. Privatize the construction method to prevent the creation of objects outside the class by calling the construction method new
private Person() {

  }

  // 2. Define a static member variable to store the unique object of this class
  private static Person p;

  // 3. Create a unique object of this class within this class
  public static synchronized Person getInstance() {
      // judge
      // If this method is called for the first time, an object of this class is created
      if (p == null) {
          p = new Person();
      }
      // If the method is not called for the first time, the object created at the time of the first call is returned
      return p;
  }

  public static void method(){}

}

```java
public class Test {
    public static void main(String[] args) {
        //Person.method();
         System.out.println(Person.getInstance());
         System.out.println(Person.getInstance());
         System.out.println(Person.getInstance());
         System.out.println(Person.getInstance());
         System.out.println(Person.getInstance());
    }
}
results of enforcement:
com.itheima.demo2_Lazy single case design mode.Person@4554617c
com.itheima.demo2_Lazy single case design mode.Person@4554617c
com.itheima.demo2_Lazy single case design mode.Person@4554617c
com.itheima.demo2_Lazy single case design mode.Person@4554617c
com.itheima.demo2_Lazy single case design mode.Person@4554617c

  • Note: the lazy single column design pattern is easy to create multiple objects in the case of multithreading, so the getInstance method needs to be locked

Chapter II multi case design mode

2.1 multi case design mode

Function of multi case design pattern

Multi case mode is a commonly used software design mode. The multi instance pattern can ensure that a fixed number of objects are generated in the class applying the pattern in the system.

To put it bluntly, the multi instance design pattern is to ensure that a fixed number of such objects will be generated for the class using this pattern

Implementation steps

​ 1. Create a class and privatize the construction method so that it cannot instantiate the class object through the new keyword outside the class.

​ 2. Generate a fixed number of objects within this class

​ 3. Provide a static method to randomly obtain an object of this class

Implementation code

// Multi instance design pattern: ensure that the class using this pattern has a fixed number of objects
public class Person {

    // 1. Privatize the construction method to prevent the outside world from calling the construction method to create objects through new
    private Person(){

    }

    // 2. Define an ArrayList set to store the Person object
    private static ArrayList<Person> list = new ArrayList<>();

    // 3. Create a fixed number of object -- > static code blocks inside the class
    static {
        for (int i = 0; i < 3; i++) {
            // Create Person object
            Person p = new Person();
            // Store Person object
            list.add(p);
        }
    }


    // 3. Provide a public static method to randomly obtain an object of this class
    public static Person getInstance(){
        // Create Random object
        Random r = new Random();
        // Generate range of random number -- > set index
        int index = r.nextInt(list.size());
        // Get element by index
        Person p = list.get(index);
        // return
        return p;
    }

}

public class Test {
    public static void main(String[] args) {
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
        System.out.println(Person.getInstance());
    }
}
results of enforcement:
com.itheima.demo3_Multi case design pattern.Person@74a14482
com.itheima.demo3_Multi case design pattern.Person@74a14482
com.itheima.demo3_Multi case design pattern.Person@1540e19d
com.itheima.demo3_Multi case design pattern.Person@677327b6
com.itheima.demo3_Multi case design pattern.Person@74a14482
com.itheima.demo3_Multi case design pattern.Person@677327b6
com.itheima.demo3_Multi case design pattern.Person@677327b6
com.itheima.demo3_Multi case design pattern.Person@677327b6
com.itheima.demo3_Multi case design pattern.Person@677327b6
com.itheima.demo3_Multi case design pattern.Person@677327b6
com.itheima.demo3_Multi case design pattern.Person@1540e19d

Chapter III enumeration

3.1 definition and use of enumeration - key points

Problems with not using enumeration

Suppose we want to define a human being, which includes name and gender. Gender is usually defined as a string type. The effect is as follows:

public class Person {
    private String name;
    private String sex;

    public Person() {
    }

    public Person(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }
	
    // Omit the get/set/toString method
}
public class Demo01 {
    public static void main(String[] args) {
        Person p1 = new Person("Zhang San", "male");
        Person p2 = new Person("Zhang San", "abc"); // Because gender is a string, we can pass in any string
    }
}

The problem of not using enumeration: you can pass any string to gender, which makes gender illegal and unsafe.

The concept of enumeration

Enumeration is a reference data type. The bottom layer of enumeration in java is a "special class" with a fixed number of objects. Therefore, if a certain type of data has a fixed value, it can be defined as an enumeration type. Such as gender, season, direction.

Defines the format of the enumeration

  • Format:

    public enum Enumeration name{
        enum ,enum ,enum ,... // Enumeration values are all letter sizes, and multiple enumeration values are separated by commas
    }
    
  • Case:

    // Gender enumeration type
    public enum Gender {
        // enum 
        MAN,WOMAN,YAO
    }
    
    // Season enumeration type
    public enum Season {
        SPRING,
        SUMMER,
        AUTUMN,
        WINTER
    }
    
    // Direction enumeration type
    public enum Direction {
        UP,
        DOWN,
        LEFT,
        RIGHT
    }
    
    

Use of enumerations

  • Format: enumeration name enum

  • Case:

    public class Person {
        String name;
        // Member variables of gender enumeration type
        Gender gender;
    
        public Person(String name, Gender gender) {
            this.name = name;
            this.gender = gender;
        }
    
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", gender=" + gender +
                    '}';
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            // Enumeration uses: enumeration name enum 
    
            // Create Person object
            Person p = new Person("Zhang San", Gender.MAN);
            System.out.println("p:" + p);
    
            // Change the gender of the p object to demon
            p.gender = Gender.YAO;
            System.out.println("p:" + p);
        }
    }
    results of enforcement:
    p:Person{name='Zhang San', gender=MAN}
    p:Person{name='Zhang San', gender=YAO}
    

3.2 other contents in enumeration (just listen)

  • The essence of enumeration is a class that uses multiple design patterns, so enumeration can also have member variables, member methods, construction methods, etc.

  • Enumeration is essentially a class. The final effect of the Sex enumeration we just defined is as follows:

    public enum Gender {
        // enum 
        MAN(10),WOMAN(20),YAO(30);
    
    
        // Member variable
        int num;
    
        // The construction method must be privatized
        private Gender(int num){
            this.num = num;
        }
    
        // Member method
        public void method(){
            System.out.println("Member method method...");
        }
    
    }
    
    public class Test {
        public static void main(String[] args) {
            // Define a variable g1 of Gender type and assign a value
            Gender g1 = Gender.MAN;
            System.out.println("num: "+g1.num);// num: 10
            g1.method();// Member method
        }
    }
    
    

Chapter IV factory design mode

4.1 overview of plant mode

Introduction to factory mode

Factory Pattern is one of the most commonly used design patterns in Java. This type of design pattern is a creation pattern, which provides the best way to create objects. Before we created class objects, we used the form of new objects. In addition to the new object method, factory mode can also create objects

Coupling degree: the relationship between classes. If the relationship is strong, high coupling; if the relationship is weak, low coupling (Development)

Requirements: there are 10 classes, and the objects of these 10 classes need to be created in the 10 test classes

Previously: create directly through new - > each test class needs to be associated with these 10 classes – (high coupling)

Factory mode: define a factory class, which is specially used to create the objects of these 10 classes, and provide methods to obtain the objects. At that time, the test class only needs to be associated with the factory class

Role of factory model

Separate the code to obtain the object from the code to create the object. The code to obtain the object does not need to create the object directly, so it does not need to care about the data required when creating the object. Just get the object through the factory class.

  • Solve the coupling problem between classes

Case demonstration

demand
  1. Write a Car interface to provide the run method

  2. Write a Falali class to implement the Car interface and rewrite the run method

  3. Write a Benchi class to implement the Car interface and rewrite the run method

    Provides a factory class that can be used to produce car objects

Implementation code

1. Write a Car interface and provide the run method

public interface Car {
    void run();
}

2. Write a Falali class to implement the Car interface and rewrite the run method

public class Falali implements Car {
    @Override
    public void run() {
        System.out.println("Ferrari is driving at 300 miles...");
    }
}

3. Write a Benchi class to implement the Car interface

public class Benchi implements Car {
    @Override
    public void run() {
        System.out.println("Mercedes Benz is driving at 200 miles...");
    }
}

4. Provide a carfactory for the production of automotive objects

// Factory class: specially created objects
public class CarFactory {

    /**
     * Create a car object
     * @param brand Automobile brand
     * @return Car object
     */
    public static Car createCar(String brand){
        if (brand.equalsIgnoreCase("Falali")){
            // Create Ferrari car object and return
            return new Falali();

        }else if (brand.equalsIgnoreCase("Benchi")){
            // Create a Mercedes Benz object and return
            return new Benchi();

        }else{
            return null;
        }

    }
}

5. Define CarFactoryTest to test automobile factory

public class Test {
    public static void main(String[] args) {
        // Do not use factory design mode -- > to get Ferrari object and Mercedes Benz object
        // Falali fl = new Falali();
        // Benchi bc = new Benchi();


        // Use factory design pattern -- > to get Ferrari object and Mercedes Benz object
        Car car1 = CarFactory.createCar("Falali");
        car1.run();

        Car car2 = CarFactory.createCar("Benchi");
        car2.run();

    }
}

Chapter V Lombok [self study expansion]

5.1 use of Lombok

lombok introduction

  • lombok can use annotations to make some code concise and convenient
  • There are some fixed codes in entity classes: construction methods, getter/setter, equals, hashcode and toString methods are all fixed. It seems troublesome to write them. Lombok can automatically generate these codes for attributes at compile time through annotation.

lombok use

​ 1. Add the jar package of lombox:

Add Lombok Jar (version used in this example: 1.18.10), add it to the module directory and add it to ClassPath

​ 2. Add lombok plug-in for IDEA (for connecting to the network)

  • First step

  • Step 2:

  • Step 3:

  • Step 4:

  1. After installation, restart IDEA.

  2. New class: Student

lombok common annotations

  • @Getter and @ Setter

    • Function: generate get and set methods of member variables.
    • Written on the member variable, it means it is valid for the current member variable.
    • Written on a class, valid for all member variables.
    • Note: static member variable is invalid.
  • @ToString:

    • Function: generate toString() method.
    • This annotation can only be written on classes.
  • @NoArgsConstructor and @ AllArgsConstructor

    • @NoArgsConstructor: nonparametric construction method.
    • @AllArgsConstructor: full parameter construction method.
    • Annotations can only be written on classes.
  • @EqualsAndHashCode

    • Function: generate hashCode() and equals() methods.
    • Annotations can only be written on classes.
  • @Data

    • Function: generate setter/getter, equals, hashCode and toString methods. If it is a final attribute, setter methods will not be generated for this attribute.

    • Annotations can only be written on classes.

  • Case:

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Person {
        private String name;
        private int age;
    
        // Construction method -- empty parameter, full parameter
        // set\get
        // toString
        // equals and hashCode
    
    }
    
    
    public class Test {
        public static void main(String[] args) {
            // Create Person object
            Person p1 = new Person();
            p1.setName("Zhang San");
            p1.setAge(18);
            System.out.println(p1.getName() + "," + p1.getAge());
            System.out.println("p1:" + p1);
    
            Person p2 = new Person("Zhang San",18);
            System.out.println(p1.equals(p2));// true
            System.out.println(p1.hashCode());// 45721950
            System.out.println(p2.hashCode());// 45721950
        }
    }
    
    

summary

Must practice:
	1.Single case design mode
    2.Multi case design pattern
    3.Defining and using enumerations
    4.Factory design mode
        
- Be able to say the benefits of singleton design pattern
  Ensure that only one object is generated in the class designed with this pattern
  step:
	1.Privatize construction methods
    2.Creates a unique object of the class inside the class
    3.Provide a public static method to get the unique object of this class
        
- Be able to say the benefits of multi instance mode
  Ensure that only a fixed number of objects are generated for classes designed using this pattern
  step:
	1.Privatize construction methods
    2.Create a fixed number of objects within the class
    3.Provide a public static method to get any object created in this class 
        
- Ability to define enumerations
  format:
		public enum Enumeration name{
            enum ,enum ,...
        }
  use: Enumeration name.enum 
      
- Ability to write in factory mode java program
   Define a class,Provide a static method,Create an object of a class in a static method and return
      

Topics: Java Programming Design Pattern