JAVA basis-design patterns (single case design pattern, decoration design pattern, template design pattern, simple factory pattern, factory method pattern)

1. Singleton design pattern

  • Singleton design pattern: Ensure that the class has only one object in memory.
  • How to ensure that the class has only one object in memory?
    (1) Control the creation of classes, and prevent other classes from creating objects of this class. That is to privatize the constructor.
    private
    (2) Define an object of this class in this class.
    Singleton s;
    (3) Provide public access methods.
    public static Singleton getInstance(){return s}
  • There are two ways to write a single case:
    (1) Hungry ChineseDevelopment in this way
	public static void main(String[] args) {
    
    
		/*
		 * Singleton s1=Singleton.s; 
		 * Singleton.s =null; 
		 * Singleton s2=Singleton.s;
		 * //如果下面设置public属性,
		 * 此时两个对象一个是调用了Single的成员变量,
		 * 一个是设置成了null。这样对象会进行修改
		 */	
		//使用饿汉式创建对象,此时我们才分为一个对象
		Singleton s1=Singleton.getSingleton();
		Singleton s2=Singleton.getSingleton();
		System.out.println(s1==s2);
	}
class  Singleton{
    
    
	//1.私有构造方法,其他类不能访问该构造方法
	private Singleton() {
    
    }
	//2.创建本类对象,如果该处使用public方式的话,会出现
	private static Singleton s =new Singleton();
	//3.对外提供公共访问发给发
	public static Singleton getSingleton() {
    
    		
//获取实例
		return s;
	}
}

The output result is: True. Because it is the same object at this time.

(2) Lazy man Interview writing this way
Don't create an object first, only create it when the user needs it. The purpose is to save space

class Singleton{
    
    
	//懒汉式,单例的延迟加载模式
	//1,私有构造函数
	private Singleton () {
    
    }
	//2,声明一个本类的引用
	private static Singleton s;
	//3,对外提供公共的访问方法
	public static Singleton getSingleton() {
    
    
		if (s==null) {
    
    
			s=new Singleton();
		}
		return s;
	}
	
}

This method has certain flaws. It will be safe when accessed by multiple threads, and multiple objects will be created.

What is the difference between hungry man and lazy man?

  1. The hungry man type is space for time (because the memory space is opened up when it comes up), and the lazy man type is time for space. (Need to judge)
  2. In multi-threaded access, the hungry man will not create multiple objects, while the lazy man may create multiple objects.

(3) The third way: the
purpose is very clear, as long as we don't change the value of s.

	class Singleton {
    
    
	private Singleton() {
    
    }
	public static final Singleton s = new Singleton();
//final是最终的意思,被final修饰的变量不可以被更改
}

2. Decorative design pattern

public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		SmartStudent smartStudent =new SmartStudent(new Student());
		smartStudent.code();
	}
	
}

interface Coder{
    
    
	public void code();
}

class Student implements Coder{
    
    
	@Override
	public void code() {
    
    
		System.out.println("JavaSE");
	}
}
class SmartStudent implements Coder{
    
    
	//1.获取被装饰类的引用
	private Student student;
	//2.在构造方法中传入被装饰类的对象
	public SmartStudent(Student student) {
    
    
		this.student = student;			//获取学生引用
	}
	//3.对原有的功能进行升级
	@Override
	public void code() {
    
    
		student.code();
		System.out.println("数据库");
		System.out.println("SSH");
	}	

The advantage of the decorative design pattern is: the coupling is not strong, and the change of the decorated class has nothing to do with the change of the decoration class

Three, Template (template) design mode

  1. Overview of template design patterns

The template method mode is to define the skeleton of an algorithm, and delay the specific algorithm to subclasses to implement

  1. pros and cons

advantage

  • Using the template method mode, while defining the algorithm skeleton, specific algorithms can be flexibly implemented to meet the flexible needs of users

Disadvantage

  • If the algorithm skeleton is modified, you need to modify the abstract class
    case (calculate a program to run for a period of time)
public class Demo1_Template {
    
    

	public static void main(String[] args) {
    
    
		Demo demo =new Demo();
		System.out.println(demo.getTime());
	}
}

abstract class GetTime{
    
    
	public final long getTime() {
    
    
		long start=System.currentTimeMillis();
		Code();
		long end=System.currentTimeMillis();
		return end-start;
	}
	public abstract void Code();
}

class Demo extends GetTime{
    
    

	@Override
	public void Code() {
    
    
		for (int i = 0; i < 100000; i++) {
    
    
			System.out.println("x");
		}
		
	}
}

4. Simple factory model

Also called the static factory method pattern, it defines a specific factory class responsible for creating instances of some classes
advantage:
The client does not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class
Disadvantages:
This static factory class is responsible for the creation of all objects. If new objects are added or some objects are created in different ways, the factory class needs to be constantly modified, which is not conducive to subsequent maintenance

Case:
Step 1: Create an interface

public abstract class Animal {
    
    
	public abstract void eat();
}

Step 2: Write cat and dog classes to implement animal interface methods

public class Dog extends Animal {
    
    
	@Override
	public void eat() {
    
    
		System.out.println("狗吃肉");
	}
}
public class Cat extends Animal {
    
    
	@Override
	public void eat() {
    
    
		System.out.println("猫吃鱼");
	}
}

Step 3: Implement the factory (user creates objects)

public class AnimalFactory {
    
    
//用于创建对象
	//public static Dog createDog() {
    
    
	//	return new Dog();
	//}
	//public static Cat createCat() {
    
    
	//	return new Cat();
	//}
	//但是该工厂会定义很多方法,需要创建很多对象。复用性太差
	//改进2.0版本
	public static Animal createAnimal(String name) {
    
    
		if ("dog".equals(name)) {
    
    
			return new Dog();
		}
		else if ("cat".equals(name)) {
    
    
			return new Cat();
		}else {
    
    
			return null;
		}
	}
}

Step 4: Do the test

public class Test {
    
    
	public static void main(String[] args) {
    
    
		//Dog d =AnimalFactory.createDog();
		Dog dog =(Dog) AnimalFactory.createAnimal("dog");
		dog.eat();
	}
}

The simple factory design pattern has an obvious drawback. When we don’t have objects that the factory should have, empty objects will be returned, and there will be pointer exceptions.

Five, the factory method model

Overview:

The abstract factory class in the factory method pattern is responsible for defining the interface for creating objects, and the creation of concrete objects is implemented by concrete classes that inherit the abstract factory.

advantage

The client does not need to be responsible for the creation of objects, thus clarifying the responsibilities of each class. If new objects are added, only a specific class and a specific factory class need to be added, which does not affect the existing code and is easy to maintain later To enhance the scalability of the system

Disadvantage

Need to write additional code, increase the workload

Case:
Step 1: Create an animal interface

public abstract class Animal {
    
    
	public abstract void eat();
}

Step 2: Create an entity class to implement interface methods

public class Cat extends Animal {
    
    
	@Override
	public void eat() {
    
    
		System.out.println("猫吃鱼");
	}
}
public class Dog extends Animal {
    
    
	@Override
	public void eat() {
    
    
		System.out.println("狗吃肉");
	}
}

Step 3: Define the factory method

public interface Factory {
    
    
	public Animal createAnimal();
}

Step 4: Open a factory to realize a cat factory and a dog factory

public class CateFactory implements Factory {
    
    
	@Override
	public Animal createAnimal() {
    
    
		
		return new Cat();
	}
}
public class DogFactory implements Factory {
    
    
	@Override
	public Animal createAnimal() {
    
    
	
		return new Dog();
	}

}

do tests:

public class TEST {
    
    
	public static void main(String[] args) {
    
    
		DogFactory dogFactory =new DogFactory();
		Dog dog =(Dog) dogFactory.createAnimal();	
		dog.eat();
		
		CateFactory cateFactory =new CateFactory();
		Cat cat =(Cat) cateFactory.createAnimal();
		cat.eat();
	}
}

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/108980116