mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-10-12 10:13:46 +00:00
* feat: implement Immutable pattern #3448 Add immutable/ module with ImmutableUser (final class, defensive copy, withAge wither method), App demo, JUnit 5 tests, PlantUML diagram, and README following project conventions. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat: add withName and withRoles wither methods to ImmutableUser #3448 Every field now has a corresponding wither for consistency. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: add junit-jupiter-api dependency to immutable module #3448 Required for @Test annotations and assert methods in test code. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
d4a0ece9e3
commit
7473378ca2
7 files changed
+531
No files matched your search
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
|
||||
*
|
||||
* The MIT License
|
||||
* Copyright © 2014-2022 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.immutable;
|
||||
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* The Immutable pattern ensures that an object's state cannot be changed after construction.
|
||||
*
|
||||
* <p>In this example, {@link ImmutableUser} demonstrates the pattern: all fields are final, the
|
||||
* mutable {@code roles} list is defensively copied, and any state change produces a brand-new
|
||||
* instance via {@link ImmutableUser#withAge(int)}.
|
||||
*/
|
||||
public class App {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
|
||||
|
||||
/**
|
||||
* Program entry point.
|
||||
*
|
||||
* @param args command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
var alice = new ImmutableUser("Alice", 30, List.of("admin", "user"));
|
||||
LOGGER.info("Original user: {}", alice);
|
||||
|
||||
var olderAlice = alice.withAge(31);
|
||||
LOGGER.info("Updated user (new object): {}", olderAlice);
|
||||
LOGGER.info("Original is unchanged: {}", alice);
|
||||
|
||||
// Demonstrate defensive copy: mutating the source list does not affect alice
|
||||
var mutableRoles = new java.util.ArrayList<>(List.of("viewer"));
|
||||
var bob = new ImmutableUser("Bob", 25, mutableRoles);
|
||||
mutableRoles.add("editor");
|
||||
LOGGER.info("Bob's roles (unchanged despite external list mutation): {}", bob.getRoles());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
|
||||
*
|
||||
* The MIT License
|
||||
* Copyright © 2014-2022 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.immutable;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* An immutable representation of a user.
|
||||
*
|
||||
* <p>All fields are final and set only at construction time. The {@code roles} list is defensively
|
||||
* copied to prevent external mutation. Any "modification" produces a new {@link ImmutableUser}
|
||||
* instance, leaving the original unchanged.
|
||||
*/
|
||||
public final class ImmutableUser {
|
||||
|
||||
private final String name;
|
||||
private final int age;
|
||||
private final List<String> roles;
|
||||
|
||||
/**
|
||||
* Constructs an {@link ImmutableUser} with the given attributes.
|
||||
*
|
||||
* @param name the user's name
|
||||
* @param age the user's age
|
||||
* @param roles the user's roles; copied defensively so external changes have no effect
|
||||
*/
|
||||
public ImmutableUser(String name, int age, List<String> roles) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.roles = List.copyOf(roles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the user's name.
|
||||
*
|
||||
* @return name
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the user's age.
|
||||
*
|
||||
* @return age
|
||||
*/
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an unmodifiable view of the user's roles.
|
||||
*
|
||||
* @return roles
|
||||
*/
|
||||
public List<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new {@link ImmutableUser} identical to this one but with the given name.
|
||||
*
|
||||
* @param newName the new name value
|
||||
* @return a new instance with the updated name
|
||||
*/
|
||||
public ImmutableUser withName(String newName) {
|
||||
return new ImmutableUser(newName, this.age, this.roles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new {@link ImmutableUser} identical to this one but with the given age.
|
||||
*
|
||||
* @param newAge the new age value
|
||||
* @return a new instance with the updated age
|
||||
*/
|
||||
public ImmutableUser withAge(int newAge) {
|
||||
return new ImmutableUser(this.name, newAge, this.roles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new {@link ImmutableUser} identical to this one but with the given roles.
|
||||
*
|
||||
* @param newRoles the new roles; copied defensively
|
||||
* @return a new instance with the updated roles
|
||||
*/
|
||||
public ImmutableUser withRoles(List<String> newRoles) {
|
||||
return new ImmutableUser(this.name, this.age, newRoles);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ImmutableUser{name='" + name + "', age=" + age + ", roles=" + roles + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
|
||||
*
|
||||
* The MIT License
|
||||
* Copyright © 2014-2022 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.immutable;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ImmutableUserTest {
|
||||
|
||||
@Test
|
||||
void constructorSetsAllFields() {
|
||||
var user = new ImmutableUser("Alice", 30, List.of("admin"));
|
||||
assertEquals("Alice", user.getName());
|
||||
assertEquals(30, user.getAge());
|
||||
assertEquals(List.of("admin"), user.getRoles());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withAgeReturnsNewObjectWithUpdatedAge() {
|
||||
var original = new ImmutableUser("Alice", 30, List.of("admin"));
|
||||
var updated = original.withAge(31);
|
||||
|
||||
assertEquals(31, updated.getAge());
|
||||
assertEquals("Alice", updated.getName());
|
||||
assertEquals(original.getRoles(), updated.getRoles());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withAgeDoesNotMutateOriginal() {
|
||||
var original = new ImmutableUser("Alice", 30, List.of("admin"));
|
||||
original.withAge(99);
|
||||
|
||||
assertEquals(30, original.getAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withAgeReturnsDistinctInstance() {
|
||||
var original = new ImmutableUser("Alice", 30, List.of("admin"));
|
||||
var updated = original.withAge(31);
|
||||
|
||||
assertNotSame(original, updated);
|
||||
}
|
||||
|
||||
@Test
|
||||
void defensiveCopyPreventsExternalListMutation() {
|
||||
var mutableRoles = new ArrayList<>(List.of("viewer"));
|
||||
var user = new ImmutableUser("Bob", 25, mutableRoles);
|
||||
|
||||
mutableRoles.add("editor");
|
||||
|
||||
assertEquals(List.of("viewer"), user.getRoles());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRolesReturnsUnmodifiableList() {
|
||||
var user = new ImmutableUser("Bob", 25, List.of("viewer"));
|
||||
|
||||
assertThrows(UnsupportedOperationException.class, () -> user.getRoles().add("editor"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void withNameReturnsNewObjectWithUpdatedName() {
|
||||
var original = new ImmutableUser("Alice", 30, List.of("admin"));
|
||||
var updated = original.withName("Bob");
|
||||
|
||||
assertEquals("Bob", updated.getName());
|
||||
assertEquals(30, updated.getAge());
|
||||
assertEquals(original.getRoles(), updated.getRoles());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withNameDoesNotMutateOriginal() {
|
||||
var original = new ImmutableUser("Alice", 30, List.of("admin"));
|
||||
original.withName("Bob");
|
||||
|
||||
assertEquals("Alice", original.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withRolesReturnsNewObjectWithUpdatedRoles() {
|
||||
var original = new ImmutableUser("Alice", 30, List.of("admin"));
|
||||
var updated = original.withRoles(List.of("viewer", "editor"));
|
||||
|
||||
assertEquals(List.of("viewer", "editor"), updated.getRoles());
|
||||
assertEquals("Alice", updated.getName());
|
||||
assertEquals(30, updated.getAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withRolesDoesNotMutateOriginal() {
|
||||
var original = new ImmutableUser("Alice", 30, List.of("admin"));
|
||||
original.withRoles(List.of("viewer"));
|
||||
|
||||
assertEquals(List.of("admin"), original.getRoles());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user