We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 2594182 commit 8ab5fe1Copy full SHA for 8ab5fe1
README.md
@@ -65,3 +65,25 @@ Classes are in the package `com.Singleton`;
65
}
66
```
67
# Pattern Factory
68
+
69
+ Factory Pattern is one of the Creational Design pattern and it's widely used in JDK as well as frameworks like
70
+Spring and Struts.
71
+This pattern is used when we have a super class with multiple sub-classes and based on the input, we need to return one of the sub-class.
72
73
+ ```java
74
+ import com.factory.FactoryClass ; //The factory class
75
+ import com.factory.PC; //sub-class
76
+ import com.factory.Server; //sub-class
77
+ //PC and Server classes extend from Computer.
78
79
+ public static void main(String[] args){
80
81
+ FactoryClass fc = new FactoryClass();
82
+ Computer comp1 = fc.getComputer("PC",16,499,4.3);
83
+ System.out.println(comp1);
84
85
86
+ Computer comp2 = fc.getComputer("Server",30,900,9);
87
+ System.out.println(comp2);
88
89
+ }
com/factory/Computer.java
@@ -0,0 +1,19 @@
1
+package com.factory;
2
3
+/**
4
+ * Created by sdmg15 on 18/03/17.
5
+ */
6
+public abstract class Computer {
7
8
9
+ public abstract String getRam();
10
+ public abstract String getCpu();
11
+ public abstract String getHdd();
12
13
+ @Override
14
15
+ public String toString(){
16
+ return "Config :: RAM = " + this.getRam() + " CPU = " + this.getCpu() + " HDD = " + this.getHdd();
17
18
19
+}
com/factory/FactoryClass.java
@@ -0,0 +1,14 @@
+public class FactoryClass {
+ public static Computer getComputer(String c, String ram, String hdd, String dd){
+ if("PC".equalsIgnoreCase(c)) return new PC(ram,hdd,dd);
+ else if("Server".equalsIgnoreCase(c)) return new Server(ram,hdd,dd);
+ return null;
com/factory/PC.java
@@ -0,0 +1,32 @@
+public class PC extends Computer {
+ private int ram;
+ private double cpu;
+ private int hdd;
+ public PC(int ram,int hdd, double cpu){
+ this.ram = ram;
+ this.hdd= hdd;
+ this.cpu = cpu;
+ public String getRam(){
+ return this.ram;
20
21
+ public String getCpu(){
22
+ return this.cpu;
23
24
25
+ public String getHdd(){
26
+ return this.hdd;
27
28
29
30
31
32
com/factory/Server.java
@@ -0,0 +1,27 @@
+public class Server extends Computer{
+ public Server(int ram,int hdd,double cpu){
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments