Summary of Simple Design Patterns

1. Design Patterns

1. Single case

1. Role

  1. Singleton mode can save objects for a long time.
  2. Singletons can transfer values: they can transfer values without any relationship between two objects, which reduces coupling and improves cohesion.

Note: Static methods are acquired through class calls, so member variables are set to static.
And when you have objects, you prevent them from passing through. Call member variables, so set to private.

2. Realization

Hungry Man: Direct Access
class SingleInstance{
	//2. Create a static privatized object of the current class inside the singleton class
    //Private: Prevents member variables from being invoked after acquiring objects
    //Static: Static method calls operate on static variables
	//Only hungry Chinese style can add final
	private final static SingleInstance s = new SingleInstance();
//1. Create constructors and privatize them
private SingleInstance() {
	
}
//3. Provide singleInstance objects through a common static approach
public static SingleInstance getSingleInstace() {
	return  s;
}
//Functional area:
int num;
public void test() {}
}
Lazy Guy: Create on Acquisition
class SingleInstance1{
	//2. Create a static privatized object of the current class inside the singleton class
	private static SingleInstance1 s = null;
//1. Create constructors and privatize them
private SingleInstance1() {	
}
//3. Provide singleInstance objects through a common static approach
public static SingleInstance1 getSingleInstace() {
	if (s == null) {
		s = new SingleInstance1();
	}
	return  s;
}
}
Example: runtime class

Each Java application has a Runtime class instance that enables the application to connect to its running environment.

2. Template design

The implementation of the function is divided into two parts, one part is determined and the other part is uncertain. Uncertain submission to subclasses, the results of subclass implementation will in turn affect the function of the deterministic part.

public class Demo4 {
    public static void main(String[] args) {
        zi z = new zi();
        z.setFood("Green grass");
        z.func();
    }
}
class fu {
    public void eat() {
    }
    public void func() {
        System.out.println("What are you going to cook?");
        eat();
    }
}
class zi extends fu {
    String food;

    public String getFood() {
        return food;
    }

    public void setFood(String food) {
        this.food = food;
    }

    public void eat() {
        System.out.println(food);
    }
}

3. Adapter mode

1. Examples

Servlet (5 method interfaces), General servlet (adapter rewrite 5 methods), httpservlet (inherit a method rewrite)

2. Attention

Can be regarded as a special decorative design pattern

4. Decoration Design Model

Decoration design pattern: provides enhanced functions based on the functions already implemented.

The origin of decorative design pattern comes from the realization of buffer flow.

Features: From the perspective of buffer flow

1. Make the original inheritance of the stream simpler

2. Increased efficiency

3. Because it improves the enhanced function on the original basis, he still belongs to the original system.

2. Website

1. Composition

  1. Function: Implementing communication between client and server
  2. http protocol: hypertext transmission protocol, which implements a communication rule between networks
  3. https protocol: secure http protocol - can be omitted, default is HTTP protocol
  4. Domain name/IP: Marking the only host on the network can simplify writing: baidu
  5. Port number: Mark a server on the same host [0,65536] - Save, default 80
  6. Resource Path: Save
  7. Query Conditions: Save

2. Attention

The server is a software, such as tomcat

3. Classification

  1. .com Business Institutions
  2. org Non-profit Organizations
  3. mil Military Institutions
  4. . net network service provider
  5. Educational institutions

6.lambda expression

Software Version Update
Additional function
Change bug
tighten security

3. Enumeration

1. Unique attributes

Default inheritance classes, so only interfaces can be implemented

Enumeration class constructors default to private methods.

Enumerations can have attributes, but attributes need to be assigned in the constructor

public class Demo4 {
    public static void main(String[] args) {
        Sex sex = Sex.woman;
        //Name is the name of sex, woman ordinal is the location, 1
        System.out.println(sex.name()+" "+sex.ordinal());
        //Equivalent to Sex.man
        Sex sex2 = Sex.valueOf("man");
        System.out.println(sex2.name()+" "+sex2.ordinal());
        //Number of input enumerations, 2 (only women and man)
        System.out.println(Sex.values().length);
    }
}

enum Sex {
    man("Man",1), woman("woman",2);
    private int num;
    private String name;
    private Sex(String name , int num ){
        this.name = name;
        this.num = num;

    }
    @Override
    public String toString() {
        return "Sex{" +
                "num=" + num +
                ", name='" + name + '\'' +
                '}';
    }
}

2.EnumSet

EnumSet<Season> enumSet = EnumSet.allOf(Season.class);
	for (Season enum1 : enumSet) {
		System.out.println("Season:"+enum1);
	}

3.EnumMap

EnumMap<Season, String> map = new EnumMap<>(Season.class);
		map.put(Season.SPRING, "spring");
		map.put(Season.SUMMER, "summer");
		map.put(Season.FULL, "Autumn");
		map.put(Season.WINTER, "winter");
		Set<Season> set = map.keySet();
		Iterator<Season> iterator = set.iterator();
		while (iterator.hasNext()) {
			Season season2 = (Season) iterator.next();
			System.out.println("EnumMap:"+map.get(season2));
		}

4. Abnormality

1. Classification:

  1. Error: Error
  2. Exception: Less serious errors in operation
    Runtime Exception
    Compile-time exceptions:

3. Throwing exceptions and generating exceptional objects can be realized by throw statement.

Throws is a declaration exception

2. The order of throwing exceptions:

From where the code exception is thrown to the jvm call exception class print

3. Characteristics:

When an exception occurs to a program, it prints the exception information and interrupts the program, so when multiple exceptions occur at the same time, by default only the first one can be executed.

4.try...catch

  1. When an exception occurs, the try code immediately interrupts and catch es are executed directly.
  2. Whether completed or not, execute final
  3. Note: When the function return s, final still executes, but exit exit does not.
  4. Exceptions caught by catch should precede subclasses

5. Custom exceptions:

Order exceptions, user exceptions, negative exceptions (usually inherited directly from Exception)

‚Äč

  class FuShuException extends Exception{
	public FuShuException() {
		// TODO Auto-generated constructor stub
	}
	public FuShuException(String message) {
		//This line of code must be written
		super(message);
	}
}
public class Demo6 {
	public static void main(String[] args) //throws FuShuException
	{
		Math4 math4 = new Math4();
		//The first way: continue to throw up, and finally give it to JVM
		//math4.div(3, -2);
		//Second: tryCatch
		try {
			math4.div(3, -2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class Math4{
	//Declare the exception and tell others that it is possible for me to have this exception.
    //When multiple exceptions need to be declared, use them directly, separate them
	public int div(int a,int b) throws FuShuException
	{
		if (b < 0) {
			throw new FuShuException("The divisor is negative.");
		}
		return a/b;
	}
}

Tags: network Spring jvm Java

Posted on Wed, 07 Aug 2019 03:00:23 -0700 by Panthers