mercredi 27 juillet 2016

Does Immutability and Singleton solves the same perpose?

What I have read is Immutability means the value once assigned remains constant, i.e. once assigned, it is reflected as the same value across the code.

Mostly Immutability is using in Functional Programming paradigm in multi threaded environment.

But.

Does singleton pattern also solves the same purpose,

Please find below of singleton written in java,

 package com.main;

class Student{
  private Student(){

  }
  public static Student INSTANCE; 
  static{
    INSTANCE = new Student();
  }

  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString(){     
    return "Student is "+this.name;
  }
}


public class SingletonTest {

  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Student student = Student.INSTANCE;
    student.setName("Arnold");

    student = Student.INSTANCE;
    student.setName("Kevin");

    student = Student.INSTANCE;
    student.setName("Jim");

    student = Student.INSTANCE;
    student.setName("Falcon");

    student = Student.INSTANCE;
    student.setName("Sarvik");


    student = Student.INSTANCE;
    System.out.println(student);

  }

}

The output of the above code is

Student is Sarvik

In an same way, I have written singleton in javaScript as well,

as follows

var Student = (function(){
  var name = "";
  var obj = {
    setName : function(studentName){
        name = studentName;
    },
    getName : function(){
        return name;
    }
  }

  return {
    INSTANCE : obj
  }
})();


var student = Student.INSTANCE;
student.setName("Arnold")

student = Student.INSTANCE;
student.setName("Kevin");

student = Student.INSTANCE;
student.setName("Jim");

student = Student.INSTANCE;
student.setName("Falcon");

student = Student.INSTANCE;
student.setName("Sarvik");

student = Student.INSTANCE;

console.log("Student is "+student.getName());

the output is as follows

rahul@rahul:~/myPractise/JavaScript-DesignPatterns$ node singleton.js 
Student is Sarvik
rahul@rahul:~/myPractise/JavaScript-DesignPatterns$ 

In both (i.e. javaScript and java) implementation of Singleton pattern you can see that the state of object remains same, it doesn't change.

Even if we reset the value of object, the output gives the latest reset value.

So does using Singleton pattern I attained Immutability in my code of object "Student" ?

Aucun commentaire:

Enregistrer un commentaire