Friend spotlight!
Whimsical Animations course
Friend spotlight!
NEW Whimsical Animations course
Friend spotlight! NEW Whimsical Animations course
huge discount only this week
Friend spotlight! Want to make your project stand out? NEW Whimsical Animations course huge discount only this week
프로토타입

Go로 작성된 프로토타입

프로토타입은 객체들​(복잡한 객체 포함)​을 그의 특정 클래스들에 결합하지 않고 복제할 수 있도록 하는 생성 디자인 패턴입니다.

모든 프로토타입 클래스들은 객체들의 구상 클래스들을 알 수 없는 경우에도 해당 객체들을 복사할 수 있도록 하는 공통 인터페이스가 있어야 합니다. 프로토타입 객체들은 전체 복사본들을 생성할 수 있습니다. 왜냐하면 같은 클래스의 객체들은 서로의 비공개 필드들에 접근할 수 있기 때문입니다.

개념적인 예시

운영 체제의 파일 시스템을 기반으로 한 예시를 사용하여 프로토타입 패턴을 연구해 봅시다. 운영 체제의 파일 시스템은 재귀적입니다: 폴더에는 파일과 폴더들이 포함되며, 내부 폴더에도 파일과 폴더 등이 포함될 수 있습니다.

각 파일과 폴더는 inode 인터페이스로 나타낼 수 있습니다. inode 인터페이스도 clone 함수가 있습니다.

파일폴더 구조체​(struct)​들은 모두 inode유형에 속하므로 printclone 함수들을 구현합니다. 또한 파일폴더 모두에서 복제 함수를 확인하세요. 두 유형 모두에 있는 복제 함수는 해당 파일 또는 폴더의 복사본을 반환합니다. 복제하는 동안 이름 필드에 키워드 '_clone'을 추가합니다.

inode.go: 프로토타입 인터페이스

package main

type Inode interface {
	print(string)
	clone() Inode
}

file.go: 구상 프로토타입

package main

import "fmt"

type File struct {
	name string
}

func (f *File) print(indentation string) {
	fmt.Println(indentation + f.name)
}

func (f *File) clone() Inode {
	return &File{name: f.name + "_clone"}
}

folder.go: 구상 프로토타입

package main

import "fmt"

type Folder struct {
	children []Inode
	name     string
}

func (f *Folder) print(indentation string) {
	fmt.Println(indentation + f.name)
	for _, i := range f.children {
		i.print(indentation + indentation)
	}
}

func (f *Folder) clone() Inode {
	cloneFolder := &Folder{name: f.name + "_clone"}
	var tempChildren []Inode
	for _, i := range f.children {
		copy := i.clone()
		tempChildren = append(tempChildren, copy)
	}
	cloneFolder.children = tempChildren
	return cloneFolder
}

main.go: 클라이언트 코드

package main

import "fmt"

func main() {
	file1 := &File{name: "File1"}
	file2 := &File{name: "File2"}
	file3 := &File{name: "File3"}

	folder1 := &Folder{
		children: []Inode{file1},
		name:     "Folder1",
	}

	folder2 := &Folder{
		children: []Inode{folder1, file2, file3},
		name:     "Folder2",
	}
	fmt.Println("\nPrinting hierarchy for Folder2")
	folder2.print("  ")

	cloneFolder := folder2.clone()
	fmt.Println("\nPrinting hierarchy for clone Folder")
	cloneFolder.print("  ")
}

output.txt: 실행 결과

Printing hierarchy for Folder2
  Folder2
    Folder1
        File1
    File2
    File3

Printing hierarchy for clone Folder
  Folder2_clone
    Folder1_clone
        File1_clone
    File2_clone
    File3_clone

다른 언어로 작성된 프로토타입

C#으로 작성된 프로토타입 C++로 작성된 프로토타입 자바로 작성된 프로토타입 PHP로 작성된 프로토타입 파이썬으로 작성된 프로토타입 루비로 작성된 프로토타입 러스트로 작성된 프로토타입 스위프트로 작성된 프로토타입 타입스크립트로 작성된 프로토타입