- Spring 5 Design Patterns
- Dinesh Rajput
- 266字
- 2021-07-08 09:59:33
Sample implementation of the Prototype design pattern
I am going to create an abstract Account class and concrete classes extending the Account class. An AccountCache class is defined as a next step, which stores account objects in a HashMap and returns their clone when requested. Create an abstract class implementing the Clonable interface.
package com.packt.patterninspring.chapter2.prototype.pattern;
public abstract class Account implements Cloneable{
abstract public void accountType();
public Object clone() {
Object clone = null;
try {
clone = super.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
Now let's create concrete classes extending the preceding class:
Here's the CurrentAccount.java file:
package com.packt.patterninspring.chapter2.prototype.pattern;
public class CurrentAccount extends Account {
@Override
public void accountType() {
System.out.println("CURRENT ACCOUNT");
}
}
Here's how SavingAccount.java should look:
package com.packt.patterninspring.chapter2.prototype.pattern;
public class SavingAccount extends Account{
@Override
public void accountType() {
System.out.println("SAVING ACCOUNT");
}
}
Let's create a class to get concrete classes in the AccountCache.java file:
package com.packt.patterninspring.chapter2.prototype.pattern;
import java.util.HashMap;
import java.util.Map;
public class AccountCache {
public static Map<String, Account> accountCacheMap =
new HashMap<>();
static{
Account currentAccount = new CurrentAccount();
Account savingAccount = new SavingAccount();
accountCacheMap.put("SAVING", savingAccount);
accountCacheMap.put("CURRENT", currentAccount);
}
}
PrototypePatternMain.java is a demo class that we will use to test the design pattern AccountCache to get the Account object by passing a piece of information, such as the type, and then call the clone() method:
package com.packt.patterninspring.chapter2.prototype
.pattern;
public class PrototypePatternMain {
public static void main(String[] args) {
Account currentAccount = (Account)
AccountCache.accountCacheMap.get("CURRENT").clone();
currentAccount.accountType();
Account savingAccount = (Account)
AccountCache.accountCacheMap.get("SAVING") .clone();
savingAccount.accountType();
}
}
We've covered this so far and it's good. Now let's look at the next design pattern.
- Flask Web全棧開發(fā)實戰(zhàn)
- Facebook Application Development with Graph API Cookbook
- 自然語言處理實戰(zhàn):預訓練模型應用及其產(chǎn)品化
- LabVIEW2018中文版 虛擬儀器程序設計自學手冊
- jQuery EasyUI網(wǎng)站開發(fā)實戰(zhàn)
- Python自動化運維快速入門
- MySQL 8 DBA基礎教程
- FFmpeg入門詳解:音視頻原理及應用
- Building an RPG with Unity 2018
- Python機器學習算法與實戰(zhàn)
- Jupyter數(shù)據(jù)科學實戰(zhàn)
- 精通MATLAB(第3版)
- Swift 4從零到精通iOS開發(fā)
- 進入IT企業(yè)必讀的324個Java面試題
- Python人工智能項目實戰(zhàn)