JAVA single embodiment, inheritance and overwriting

What is a singleton

Class singleton object must ensure that there is only one strength ---- This is the definition of a single case of Wikipedia, this can also be realized as a code of intent Singleton pattern standard test.

Singleton divided into two categories
1. lazy formula: refers to a single instance of the global construction embodiment when first used.
2. starving the formula: refers to a single instance of the global embodiment constructed when the class is loaded.
Normally we use more singleton is lazy style

The following details about the difference between the two
1. lazy style:
simple wording
// Code 1

public class Single1 {
    private static Single1 instance;
    public static Single1 getInstance() {
        if (instance == null) {
            instance = new Single1();
        }
        return instance;
    }
}
//代码1.1
public class Single1 {
    private static Single1 instance;
    //将构造方法变成私有的
    private Single1() {}
    public static Single1 getInstance() {
    //判断是否已有实例对象
        if (instance == null) {
            instance = new Single1();
        }
        return instance;
    }
}

This approach, in most cases there is no problem, however, when the multi-line support work if run into if (instance == null), have judged that the empty, it will also create cool threads example, does not belong to a single embodiment.

synchronized version

synchronized version
in order to modify the above problem, we add a synchronization lock, modify the code as follows:

// code 2

public class Single2 {
    private static Single2 instance;
    private Single2() {}
    public static synchronized Single2 getInstance() {
        if (instance == null) {
            instance = new Single2();
        }
        return instance;
    }
}

We added on a basis of the originalsynchronizedAfter the keyword,getInstanceThe method will be locked, and if they execute two threads at the same time this method, there will be a lock to get synchronous execution method, you need to wait another big finish after the first execution, will perform a second. Doing so avoids possible because of multithreaded result in multiple instances.
But this method also has a problem:gitInstanceLock method, although it will avoid multiple instances of problems that may occur, but will be mandatory for all threads except T1 wait, in fact, would adversely affect the efficiency of the program.

Double-check (Double-Check) version

Code 2 1 with respect to the efficiency of the code, in fact, is a 1% chance to solve the problem, and the use of a 100% occurrence of protective shield. It has an optimized idea, is to appear in 100% protective shield, also appear to 1% chance to make it appear only in place could result in multiple instances occur.
--- We use the following methods to solve this problem:

// Code 3

public class Single3 {
    private static Single3 instance;
    private Single3() {}
    public static Single3 getInstance() {
        if (instance == null) {
            synchronized (Single3.class) {
                if (instance == null) {
                    instance = new Single3();
                }
            }
        }
        return instance;
    }
}

This method is relatively complex, which appears twice if (instancenull), the judge, this is calledDouble check ==

The first if (instance == null) to solve the problem in the efficiency of the code 2, only when the instance is null, before entering the synchronized code block, greatly reducing the machine filter

The second if (instance == null), in order to prevent occurrence of multiple instances.

To our code look more perfect, we have made some deal with the ultimate version of the code is as follows:

The ultimate version: volatile

// Code 4

public class Single4 {
    private static volatile Single4 instance;
    private Single4() {}
    public static Single4 getInstance() {
        if (instance == null) {
            synchronized (Single4.class) {
                if (instance == null) {
                    instance = new Single4();
                }
            }
        }
        return instance;
    }
}

volatileThe Key field is prohibited instruction reordering (in the case does not affect the end result, the order of execution of some statements may have to be adjusted.), After the instance is declared as volatile, it will have a write memory barrier so, before the completion of its assignment, it would not be calling the read operation.

note: Volatile Blocked not singleton = new Singleton () command internal rearrangement of words, but to ensure that before the completion of an operation, does not call read (if (instance == null)).

2. starving type:

Because class loading process is performed by the class loader, this process is to ensure synchronization by the JVM, so this way there is an inherent advantage - the ability of immune many problems caused by multiple threads.

Method is as follows:

public class SingleB {
    private static final SingleB INSTANCE = new SingleB();
    private SingleB() {}
    public static SingleB getInstance() {
        return INSTANCE;
    }
}

For Singleton starving style, this code can be said to be perfect, so it appears the problem is the problem of starving itself of a single example - due INSTANCE initialization is carried out when the class is loaded, and the class is loaded by the ClassLoader to do, so developers had for its initialization time it is difficult to accurately grasp.

Knowledge Point: What time is when the class is loaded?

  1. When a new Object
  2. When you create an instance of it using reflection
  3. When a subclass is loaded, if the parent class has not been loaded, to load the parent class
  4. The main class executed when jvm startup will first be loaded
  5. Other implementations
    five methods above will trigger class is loaded.

Effective Java1 static inner classes

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton (){}
    public static final Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

The wording of the internal classSingletonHolderIt is a single formula starving embodiment implemented, inSingletonHolderWhen will the initializationClassLoaderTo ensure synchronization, theINSTANCETrue is a singleton. Also, becauseSingletonHolderIt is an internal class, only the outer classSingletonThe == getInstance ()It is using, so it is the timing that is loadedgetInstance () method when == was first called.

Effective Java 2 Enumeration

public enum SingleInstance {
    INSTANCE;
    public void fun1() { 
        // do something
    }
}

This approach makes the code more concise, but also to solve most of the problem, the idea is very good. But in the succession scenario, it is not quite apply.

-------------------------------------------------- ---------------------Dividing line--------------------------- -------------------------------------------------- -----

inherit

Syntax **: ** modifier SubClass the extends the SuperClass {
// class definition part
}

Inheritance is achieved by the extends keyword, which SunClass called a subclass, SuperClass called the parent class,
the base class or super class, modifiers, if it is public, then the class is visible throughout the project, without public modifier, This class only in the current package courseware, can not use private and protected modifiers.

Pet abstracted classes are as follows:

/**
 * 宠物类,狗狗和企鹅的父类
 *
 */
public class Pet {
	private String name="无名氏";//昵称
	private int health=100;//健康值
	private int love=0;//亲密度
	/**
	 * 无参构造方法
	 * @param name2 
	 */
	public Pet(){
		this.health=95;
		System.out.println("执行宠物的无参构造方法");
	}
	/**
	 * 有参构造方法
	 */
	public Pet(String name){
		this.name=name;
	}
	public String getName() {
		return name;
	}
	public int getHealth() {
		return health;
	}
	public int getLove() {
		return love;
	}
	/**
	 * 输出宠物信息
	 */
	public void print(){
		System.out.println("宠物的自白:\n我的名字叫"+this.name+",健康值是"+this.health+",和主人的亲密度是"+this.love+"。");
	}
}

Pet Dog class inherits class code as follows:

/**
 * 狗狗类,宠物的子类
 */
public class Dog extends Pet{
	private String strain;//品种
	/**
	 * 有参构造方法
	 */

	public Dog(String name,String strain) {
		super(name);//此处不能用this.name=name
		this.strain = strain;
	}
	public String getStrain() {
		return strain;
	}

Penguin class inherits Pet, code as follows:

/**
 * 企鹅类,宠物的子类
 */
public class Penguin extends Pet{
	private String sex;//品种
	/**
	 * 有参构造方法
	 */

	public Penguin(String name,String sex) {
		super(name);//此处不能用this.name=name
		this.sex = sex;
	}
	public String getSex() {
		return sex;
	}

Write test classes are as follows:

public class TestPet {

	public static void main(String[] args) {
		//1.创建宠物对象pet并输出信息
		Pet pet=new Pet("贝贝");
		pet.print();
		//创建狗狗对象dog并输出信息
		Dog dog=new Dog("欧欧","雪纳瑞");
		dog.print();
		//创建企鹅对象pgn并输出信息
		Penguin pgn=new Penguin("楠楠","Q妹");
		pgn.print();
		
	}

}

Results are as follows:
Here Insert Picture DescriptionWhat is inherited
Inheritance is one of the three characteristics of object-oriented, is an important means to achieve java code reuse. java only supports single inheritance, that is, each class can have only one direct parent. Inheritance is expressed is a relationship, or a kind of special and general relations, such as the Dog is a Pet. Similarly, you can allow students to heirs inherit Apple Fruit, make a triangle integrated geometry.

In java, a subclass can inherit from a parent class to those of "property" mean?
1. inherited public and protected modified properties and methods, regardless of whether the parent class and subclass in the same package.
2. inherits default permissions modified modifier properties and methods, but the parent class and subclass must be in the same package.
3. modification can not be inherited private properties and methods.
4. The method of construction can not be inherited parent class.

Here is a summary of what access the access modifier
Here Insert Picture Description

Constructor rewrite and inheritance relations

Dog class parent class override print () method, as follows:

/**
 * 狗狗类,宠物的子类
 */
public class Dog extends Pet{
	private String strain;//品种
	/**
	 * 有参构造方法
	 */

	public Dog(String name,String strain) {
		super(name);//此处不能用this.name=name
		this.strain = strain;
	}
	public String getStrain() {
		return strain;
	}
	/**
	 * 重写父类的print()方法
	 */
	public void print(){
		super.print();//调用父类的print()方法
		System.out.println("我是一只"+this.strain+"。");
	}
}

Penguin parent class override print () method, as follows:

/**
 * 企鹅类,宠物的子类
 */
public class Penguin extends Pet{
	private String sex;//品种
	/**
	 * 有参构造方法
	 */

	public Penguin(String name,String sex) {
		super(name);//此处不能用this.name=name
		this.sex = sex;
	}
	public String getSex() {
		return sex;
	}
	/**
	 * 重写父类的print()方法
	 */
	public void print(){
		super.print();//调用父类的print()方法
		System.out.println("性别是"+this.sex+"。");
	}
}

Results are as follows:
Here Insert Picture Description
Method overrides the conditions to be met:
1. override method and the override method must have the same method name.
2. The method of rewriting and the rewritten method must have the same list of parameters.
3. The method of rewriting of the same type of return value is rewritten and the return value type or a subclass thereof.
4. override the method can not be rewritten narrow access method.

Overloading and rewrite What is the difference and contact
1. Overload relates to a method of the same class with the same name, the same method name required, different parameter list. And return type, irrespective of access modifiers.
Design rewriting between the same method on the parent class and subclass, the method requires the same name, the same parameter list, return the same value type (or subclasses), access to the parent class modifier can not be strict.

If the parent class method is overridden in a subclass want to call, how to achieve it?
"Super method name" implemented in sub-class method by
super must appear in the sub-class (methods and constructors subclass), rather than other locations.
Members can access the parent class, such properties of the parent class, method, constructor.
Note restrict access privileges, such as can not access private members through super.

Released three original articles · won praise 0 · Views 100

Guess you like

Origin blog.csdn.net/lily15241/article/details/105043084