Lesson: Design Patterns

                                                                    Singleton 

-- Constructor protected olduqda, o zaman singleton design pattern-i qirmaq olur. Bunun ucun araliq bir class yaradiriq ve esas class-i extend edirik.

package org.singleton;

public class Test {

private static Test test = null;

private Test() {}

public static Test getInstance() {
if(test == null)
test = new Test();
return test;
}
}


package com.example.ms7.creational_patterns;

public final class Singleton {
private static Singleton instance;

private Singleton() {
}

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


-- Immutable class

package org.singleton;

public class Teacher {
public String name;
}
package org.singleton;

public class Person {

private static Person person = null;

private Teacher t = null;

private Person() {
}

public Person(Teacher t) {
this.t = t;
}

public static Person instance() {
if (person == null)
person = new Person();
return person;
}

public Teacher getM() {
Teacher tt = new Teacher();
tt.name = t.name;
return tt;
}
}
package org.singleton;

public class Main {
public static void main(String[] args) {
Teacher mercedes = new Teacher();
Person person = new Person(mercedes);
mercedes.name = "abc";

System.out.println(person.getM().name);

person.getM().name = "asdfasdf";
System.out.println(person.getM().name);
}
}













 





Комментарии

Популярные сообщения из этого блога

IoC:ApplicationContext, BeanFactory. Bean

Lesson1: JDK, JVM, JRE

Lesson_2: Operations in Java