You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
publicclassHistogramChartimplementsChart {
publicHistogramChart() {
System.out.println("Create the histogram chart .");
}
publicvoiddisplay() {
System.out.println("Display the histogram chart .");
}
}
(3)PieChart : 饼状体类,充当具体产品类.
publicclassPieChartimplementsChart {
publicPieChart() {
System.out.println("Create the pie chart .");
}
publicvoiddisplay() {
System.out.println("Display the pie chart .");
}
}
(4)LineChart : 折线图类,充当具体产品类.
publicclassLineChartimplementsChart {
publicLineChart() {
System.out.println("Create the line chart .");
}
publicvoiddisplay() {
System.out.println("Display the line chart .");
}
}
(5)ChartFactory : 图表工厂类,充当工厂类.
publicclassChartFactory {
publicstaticChartgetChart(StringchartType) {
Chartchart = null;
if (chartType.equalsIgnoreCase("histogram")) {
chart = newHistogramChart();
System.out.println("Initialize the histogram chart .");
} elseif (chartType.equalsIgnoreCase("pie")) {
chart = newPieChart();
System.out.println("Initialize the pie chart .");
} elseif (chartType.equalsIgnoreCase("line")) {
chart = newLineChart();
System.out.println("Initialize the line chart .");
} else {
System.err.println("error : Please chakout your object name. ");
}
returnchart;
}
}
(6)SimpleFactoryPatternTest : 客户端测试类
publicclassSimpleFactoryPatternTest {
publicstaticvoidmain(String[] args) {
Chartchart = ChartFactory.getChart("histogram");
chart.display();
Chartchart2 = ChartFactory.getChart("pie");
chart2.display();
Chartchart3 = ChartFactory.getChart("line");
chart3.display();
/*##The result be shown as followed:## Create the histogram chart . Initialize the histogram chart . Display the histogram chart . Create the pie chart . Initialize the pie chart . Display the pie chart . Create the line chart . Initialize the line chart . Display the line chart . */
}
}
开闭原则 : 软件实体应当对扩展开放,对修改关闭.
Open-Closed Principle(OCP) : Software entities should be open for extension,but closed for modification.
在开闭原则的定义中,软件实体可以指一个软件模块,一个由多个类组成的局部结构或一个独立的类,开闭原则就是指软件实体应尽量在不修改
原有代码的情况下进行扩展.