인스턴스의 상태를 그대로 파일 저장하거나 네트웍으로 전송하고 (serialization) 이를 다시 복원(deserialization)하는 방식
자바에서는 보조 스트림을 활용하여 직렬화를 제공
ObjectInputStream과 ObjectOutputStream
class Person implements Serializable{
private static final long serialVersionUID = -1503252402544036183L;
String name;
String job;
public Person() {}
public Person(String name, String job) {
this.name = name;
this.job = job;
}
public String toString()
{
return name + "," + job;
}
}
public class SerializationTest {
public static void main(String[] args) throws ClassNotFoundException {
Person personAhn = new Person("이순신", "대표이사");
Person personKim = new Person("김유신", "상무이사");
try(FileOutputStream fos = new FileOutputStream("serial.out");
ObjectOutputStream oos = new ObjectOutputStream(fos)){
oos.writeObject(personAhn);
oos.writeObject(personKim);
}catch(IOException e) {
e.printStackTrace();
}
try(FileInputStream fis = new FileInputStream("serial.out");
ObjectInputStream ois = new ObjectInputStream(fis)){
Person p1 = (Person)ois.readObject();
Person p2 = (Person)ois.readObject();
System.out.println(p1);
System.out.println(p2);
}catch (IOException e) {
e.printStackTrace();
}
}
}
class Person implements Externalizable{
String name;
String job;
public Person() {}
public Person(String name, String job) {
this.name = name;
this.job = job;
}
public String toString()
{
return name + "," + job;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(name);
//out.writeUTF(job);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = in.readUTF();
//job = in.readUTF();
}
}
public class FileTest {
public static void main(String[] args) throws IOException {
File file = new File("D:\\JAVA_LAB\\Chapter6\\newFile.txt");
file.createNewFile();
System.out.println(file.isFile());
System.out.println(file.isDirectory());
System.out.println(file.getName());
System.out.println(file.getAbsolutePath());
System.out.println(file.getPath());
System.out.println(file.canRead());
System.out.println(file.canWrite());
file.delete();
}
}
public class RandomAccessFileTest {
public static void main(String[] args) throws IOException {
RandomAccessFile rf = new RandomAccessFile("random.txt", "rw");
rf.writeInt(100);
System.out.println("파일 포인터 위치:" + rf.getFilePointer());
rf.writeDouble(3.14);
System.out.println("파일 포인터 위치:" + rf.getFilePointer());
rf.writeUTF("안녕하세요");
System.out.println("파일 포인터 위치:" + rf.getFilePointer());
rf.seek(0); //-파일 포인터 위치를 이동 시킬 수 있음
System.out.println("파일 포인터 위치:" + rf.getFilePointer());
int i = rf.readInt();
double d = rf.readDouble();
String str = rf.readUTF();
System.out.println("파일 포인터 위치:" + rf.getFilePointer());
System.out.println(i);
System.out.println(d);
System.out.println(str);
}
}
Decorator Pattern을 활용하여 커피를 만들어 봅시다.
아메리카노
카페 라떼 = 아메리카노 + 우유
모카 커피 = 아메리카노 + 우유 + 모카시럽
크림 올라간 모카커피 = 아메리카노 + 우유 + 모카시럽 + whipping cream
커피는 컴포넌트고, 우유, 모카시럽, whipping cream은 모두 데코레이터임