官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 建湖县| 修武县| 荥阳市| 洛宁县| 札达县| 哈尔滨市| 玉树县| 玉山县| 鄂温| 漳浦县| 贡嘎县| 康保县| 丹江口市| 略阳县| 东乡族自治县| 土默特左旗| 平昌县| 黔南| 青龙| 石阡县| 福贡县| 黔南| 图木舒克市| 太和县| 老河口市| 克山县| 靖江市| 东至县| 峡江县| 霍林郭勒市| 宣威市| 鄂州市| 潜山县| 手机| 布拖县| 汤阴县| 泰兴市| 阜南县| 六盘水市| 堆龙德庆县| 五华县|