2022/02/26 자바의 다양한 기능들

김석진·2022년 2월 26일
0

직렬화(serialization)

serialization이란?

  • 인스턴스의 상태를 그대로 파일 저장하거나 네트웍으로 전송하고 (serialization) 이를 다시 복원(deserialization)하는 방식

  • 자바에서는 보조 스트림을 활용하여 직렬화를 제공

  • ObjectInputStream과 ObjectOutputStream

Serializable 인터페이스

  • 직렬화는 인스턴스의 내용이 외부로 유출되는 것이므로 프로그래머가 해당 객체에 대한 직렬화 의도를 표시해야 함
  • 구현 코드가 없는 marker interface
  • transient: 직렬화 하지 않으려는 멤버 변수에 사용함(Socket등 직렬화 할 수 없는 객체)
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();
		}
	}
}

Externalizable 인터페이스

  • writeExternal()과 readExternal() 메서드를 구현해야함
  • 프로그래머가 직접 객체를 읽고 쓰는 코드를 구현할 수 있음
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();
	}
	
}

그 외 여러가지 입출력 클래스들

File 클래스

  • 파일 개념을 추상화한 클래스
  • 입출력 기능은 없고, 파일의 이름 ,경로 , 읽기 전용등의 속성을 알 수 있음
  • 이를 지원하는 여러 메서드들이 제공됨
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();
	}
}

RandomAccessFile 클래스

  • 입출력 클래스 중 유일하게 파일에 대한 입력과 출력을 동시에 할 수 있는 클래스
  • 파일 포인터가 있어서 읽고 쓰는 위치의 이동이 가능함
  • 다양한 메서드가 제공됨
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

  • 자바의 입출력 스트림은 decorator pattern임
  • 여러 decorator들을 활용하여 다양한 기능을 제공
  • 상속 보다 유연한 구현방식
  • 데코레이터는 다른 데코레이터나 또는 컴포넌트를 포함해야함
  • 지속적인 기능의 추가와 제거가 용이함
  • decorator와 component(실제로 I/O를 할 수 있는것)는 동일한 것이 아님( 기반 스트림 클래스가 직접 읽고 쓸수 있음, 보조 스트림은 추가적인 기능 제공)

커피를 만들어보기

Decorator Pattern을 활용하여 커피를 만들어 봅시다.
아메리카노
카페 라떼 = 아메리카노 + 우유
모카 커피 = 아메리카노 + 우유 + 모카시럽
크림 올라간 모카커피 = 아메리카노 + 우유 + 모카시럽 + whipping cream
커피는 컴포넌트고, 우유, 모카시럽, whipping cream은 모두 데코레이터임

profile
주니어 개발자 되고싶어요

0개의 댓글