Skip to content

Instantly share code, notes, and snippets.

@chermehdi
Created November 7, 2016 14:09
Show Gist options
  • Save chermehdi/8a6b2b1b74e793dcb12f2280553eae2b to your computer and use it in GitHub Desktop.
Save chermehdi/8a6b2b1b74e793dcb12f2280553eae2b to your computer and use it in GitHub Desktop.
an Example for a Simple Immutable Object
public final class MyImmutableObject {
/**
* Both String and Integer Classes Are Immutable
*/
private final String ObjectName;
private final Integer ObjectId;
/**
* private Constructors so No Unplanned Constructions of an Object Occurs
*
* @param ObjectName
* @param ObjectId
*/
private MyImmutableObject(String ObjectName, Integer ObjectId) {
this.ObjectName = ObjectName;
this.ObjectId = ObjectId;
}
/**
* to Create New Instances of the Immutable Object You Must pass by this
* method kind of a factory design pattern
*
* @param ObjectName
* @param ObjectId
* @return
*/
public static MyImmutableObject getNewInstance(String ObjectName, Integer ObjectId) {
return new MyImmutableObject(ObjectName, ObjectId);
}
// getter methods after all we have read access to an Immutable Object
public Integer getObjectId() {
return ObjectId;
}
public String getObjectName() {
return ObjectName;
}
/**
* for Debugging
*/
public String toString() {
return ObjectId + " " + ObjectName;
}
public static void main(String[] args) {
MyImmutableObject obj = MyImmutableObject.getNewInstance("MyObject", 1);
System.out.println(obj);
modify(obj.getObjectId(), obj.getObjectName());
System.out.println(obj);
}
public static void modify(Integer ObjectId, String ObjectName) {
ObjectId = 2;
ObjectName = "MyObjectModified";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment