- 팩토리 패턴을 사용하면 함수를 호출하는 것으로 객체를 만들 수 있다. new 키워드를 사용하는 대신 함수 호출의 결과로 객체를 만들 수 있는 것이다.
장점
- 동일한 프로퍼티를 가진 여러 작은 객체를 만들어낼 때 유용하다.
- 유사한 반복 작업을 하는 객체를 만드는 것이 팩토리 패턴의 주요 목적이다.
단점
- 대부분의 상황에서 객체를 일일히 만드는 것보다 클래스를 활용하는 편이 메모리를 절약하는 데 더 효과적이다.
예제 코드) chart
import React from 'react';
// Chart Factory
function createChart(chartType, data) {
switch (chartType) {
case 'bar':
return new BarChart(data);
case 'line':
return new LineChart(data);
case 'pie':
return new PieChart(data);
default:
return null;
}
}
// Chart Classes (Using a common 'draw' method)
function BarChart(data) {
this.data = data;
this.draw = function () {
console.log('Drawing Bar Chart with data:', this.data);
// Logic to draw a Bar Chart with 'data'
};
}
function LineChart(data) {
this.data = data;
this.draw = function () {
console.log('Drawing Line Chart with data:', this.data);
// Logic to draw a Line Chart with 'data'
};
}
function PieChart(data) {
this.data = data;
this.draw = function () {
console.log('Drawing Pie Chart with data:', this.data);
// Logic to draw a Pie Chart with 'data'
};
}
// Chart Component in React
function Chart({ chartType, chartData }) {
const chart = createChart(chartType, chartData);
React.useEffect(() => {
if (chart) {
chart.draw();
}
}, [chart]);
return </>;
}
// Usage
const chartData = [10, 20, 15, 30];
const userChartType = 'bar';
function App() {
return (
<div>
<h1>Chart Library</h1>
<Chart chartType={userChartType} chartData={chartData} />
</div>
);
}
export default App;
📚 참고자료
'배워서 남 주자' 카테고리의 다른 글
디자인 패턴 - Proxy 패턴 (2) | 2023.10.17 |
---|---|
디자인 패턴 - Provider 패턴 (0) | 2023.10.15 |
디자인 패턴 - Prototype 패턴 (0) | 2023.10.11 |
디자인 패턴 - Singleton 패턴 (0) | 2023.10.08 |
디자인 패턴 - introduction (1) | 2023.10.08 |