• 1_불변 객체(Immutable Object)
    : String은 이미 불변 객체로 정의돼있다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    package kr.co.ioacademy; //iocademy 윤찬식 강사님
     
    // Java 의 클래스 = 레퍼런스 타입
    // : 객체는 힙에 생성된다.
     
    // Immutable Object(불변 객체)
    // 장점
    // 1. 생성자의 방어 복사 및 접근 메소드의 방어 복사가 필요없다.
    // 2. 병렬 프로그래밍을 작성할 때, 동기화 없이 객체를 공유 가능하다.
    //   "특별한 이유가 없다면 객체를 불변 객체로 설계해야 한다."
    //    : Effective Java, Effective Objective-C
     
    // 단점
    // 객체가 가지는 값마다 새로운 객체가 필요하다.
    // String s += "xxx";   // "Helloxxx"
    //  : 내용이 동일한 객체는 공유되는 메커니즘을 제공해야 한다.(Flyweight)
    //    - static factory method
     
    // 불변 클래스를 만드는 방법
    // 1. 객체를 변경하는 setter 를 제공하지 않습니다.
    // 2. 모든 필드를 final
    // 3. 가변 객체 참조 필드를 사용자가 얻을 수 없도록 해야 한다 (private)
    // 4. 상속 금지 (final class, final method, 생성자를 private 으로 정의하고 public static factory method를 제공)
     
    public class Example1 {
        public static void main(String[] args) {
            Point pos = new Point(10, 20);
     
            // Integer i;
     
            Rect r = new Rect(pos);
            // pos.setY(100);    // 공격!
     
            pos = r.getPosition();
            // pos.setX(-9999);
     
            String s = r.getName();
            s = "xxx";
     
            System.out.println(r);
        }
    }
     
    // String, Integer, Long ... : Immutable Object
     
    class Rect {
        // 캡슐화, 정보 은닉
        private final Point position;
        private String name;
     
        public Rect(Point position) {
            this.position = position.clone();
            this.name = "Tom";
        }
     
        public String getName() {
            return name;
        }
     
        public Point getPosition() {
            return position.clone();
        }
     
        @Override
        public String toString() {
            return "Rect{" +
                    "position=" + position +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
     
     
    class Point implements Cloneable {
        final int x;
        final int y;
     
        @Override
        public Point clone() {
            try {
                return (Point) super.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return null;
        }
     
     
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
     
        public int getX() {
            return x;
        }
     
        public int getY() {
            return y;
        }
        /*
        public void setX(int x) {
            this.x = x;
        }
     
        public void setY(int y) {
            this.y = y;
        }
        */
     
        @Override
        public String toString() {
            return "Point{" +
                    "x=" + x +
                    ", y=" + y +
                    '}';
        }
    }

  • 2_불변 객체
    : final로 선언된 배열은 변하지 않지만, 배열 안의 데이터가 변할수 있다. -> VALUES 는 변하지 않지만 VALUE 안에 데이터가 변할수가 있다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    package kr.co.ioacademy; //iocademy 윤찬식 강사님
     
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Collections;
     
    public class Example2 {
        /*
        private static final Integer[] VALUES =
                { 1, 2, 3, 4, 5 };
     
        // 해결 방법 1. 방어 복사본
        public static Integer[] values() {
            return VALUES.clone();
        }
        */
     
        // 해결 방법 2. 수정불가 컬렉션 사용 - UnsupportedOperationException
        private static final Integer[] PRIVATE_VALUES = {1, 2, 3, 4, 5};
        public static final Collection<Integer> VALUES =
                Collections.unmodifiableCollection(Arrays.asList(PRIVATE_VALUES));
     
        public static void main(String[] args) {
            Collection<Integer> arr = Example2.VALUES;
            arr.add(10);
     
            for (Integer e : VALUES) {
                System.out.println(e);
            }
        }
    }


'Programing > Java' 카테고리의 다른 글

Effective Java - 스레드(2)  (0) 2016.03.07
Effective Java - 스레드(1)  (0) 2016.03.07
Effective Java - 객체 비교, 복제  (0) 2016.03.04
Effective Java - 객체 소멸  (0) 2016.03.04
Junit 사용하기  (0) 2016.03.03

+ Recent posts