- 특정 타입의 객체들을 중앙에 관리하고 접근할 수 있게 해주는 패턴
- 즉, 객체를 전역적으로 관리하고 제공한다.
- 중앙 저장소(레지스트리)를 통해, 객체를 관리하고 필요할 때 조회하여 사용한다.
사용 사례
- 플러그인 시스템 구현
- 의존성 주입 컨테이너
- 컴포넌트 관리 시스템
예시
- 컴포넌트 레지스트리를 만들고, 해당 컴포넌트를 레지스트리로부터 가져오는 로직을 만들어볼 수 도 있다.
- 핵심 아이디어는, '동적으로' 객체를 관리한다는 것이다. 즉, 객체를 전역적으로 저장해두고, 조회 메서드를 통해 조회하는 것.
type ComponentRegistry = {
[key: string]: React.ComponentType<any>;
};
class SectionRegistry {
private static instance: SectionRegistry;
private registry: ComponentRegistry = {};
private constructor() {}
public static getInstance(): SectionRegistry {
if (!SectionRegistry.instance) {
SectionRegistry.instance = new SectionRegistry();
}
return SectionRegistry.instance;
}
public register(name: string, component: React.ComponentType<any>): void {
this.registry[name] = component;
}
public get(name: string): React.ComponentType<any> | undefined {
return this.registry[name];
}
public getAll(): ComponentRegistry {
return { ...this.registry };
}
}
// 사용 예시
const registry = SectionRegistry.getInstance();
// 섹션 등록
registry.register('HeaderSection', HeaderSection);
registry.register('FooterSection', FooterSection);
// 섹션 사용
const DynamicSection: React.FC<{ name: string }> = ({ name }) => {
const Section = registry.get(name);
return Section ? <Section /> : null;
};
// 모든 등록된 섹션 렌더링
const AllSections: React.FC = () => {
const sections = registry.getAll();
return (
<>
{Object.entries(sections).map(([name, Section]) => (
<Section key={name} />
))}
</>
);
};