Created
November 7, 2016 14:09
-
-
Save chermehdi/8a6b2b1b74e793dcb12f2280553eae2b to your computer and use it in GitHub Desktop.
an Example for a Simple Immutable Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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