Prototype design pattern in Java

Posted u013063153

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Prototype design pattern in Java相关的知识,希望对你有一定的参考价值。

package com.design.prototype;

/**
 * Prototype design pattern in Java
 */
public class Book 
    private int bid;
    private String bname;

    public int getBid() 
        return bid;
    

    public void setBid(int bid) 
        this.bid = bid;
    

    public String getBname() 
        return bname;
    

    public void setBname(String bname) 
        this.bname = bname;
    

    @Override
    public String toString() 
        return "Book" +
                "bid=" + bid +
                ", bname='" + bname + '\\'' +
                '';
    

package com.design.prototype;

import java.util.ArrayList;
import java.util.List;

/**
 * Prototype design pattern in Java
 */
public class BookShop implements Cloneable 
    private String shopName;
    List<Book> books = new ArrayList<>();

    public String getShopName() 
        return shopName;
    

    public void setShopName(String shopName) 
        this.shopName = shopName;
    

    public List<Book> getBooks() 
        return books;
    

    public void setBooks(List<Book> books) 
        this.books = books;
    

    public void loadData() 
        for (int i = 1; i <= 10; i++) 
            Book b = new Book();
            b.setBid(i);
            b.setBname("Book " + i);
            getBooks().add(b);
        
    

    @Override
    public String toString() 
        return "BookShop" +
                "shopName='" + shopName + '\\'' +
                ", books=" + books +
                '';
    

    @Override
    protected Object clone() throws CloneNotSupportedException 
        BookShop shop = new BookShop();

        for (Book b : getBooks()) 
            shop.getBooks().add(b);
        

        return shop;
    

package com.design.prototype;

/**
 * Prototype design pattern in Java
 */
public class Demo 
    public static void main(String[] args) throws CloneNotSupportedException 
        BookShop bs = new BookShop();
        bs.setShopName("Novelty");
        bs.loadData();
        
        BookShop bs1 = (BookShop) bs.clone();
        bs1.setShopName("A1");
        bs.getBooks().remove(2);
        System.out.println(bs);
        System.out.println(bs1);

    


以上是关于Prototype design pattern in Java的主要内容,如果未能解决你的问题,请参考以下文章

Prototype Design Pattern

[design pattern] Category

Pattern design

[Design Pattern] Adapter Design Pattern

MVVM design pattern

[Design Pattern] DAO Pattern 简单案例