图解设计模式Prototype模式

UML

图解设计模式Prototype模式_第1张图片
Paste_Image.png
Product
//原型
public interface Product extends Cloneable {
     void use(String s);
     Product createClone();
}

MessageBox
//具体的原型
public class MessageBox implements Product {

    private char decochar;
    public MessageBox(char decochar) {
        this.decochar = decochar;
    }
    @Override
    public void use(String s) {
        int length = s.getBytes().length;
        for (int i = 0; i < length + 4; i++) {
            System.out.print(decochar);
        }
        System.out.println();
        System.out.println(decochar + " " + s + " " + decochar);
        for (int i = 0; i < length + 4; i++) {
            System.out.print(decochar);
        }
        System.out.println("");
    }

    @Override
    public Product createClone() {
        Product p = null;
        try {
            p = (Product)clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return p;
    }
}

UnderlinePen
//具体的原型
public class UnderlinePen implements Product {
    private char ulchar;
    public UnderlinePen(char ulchar) {
        this.ulchar = ulchar;
    }
    @Override
    public void use(String s) {
        int length = s.getBytes().length;
        System.out.println("\"" + s + "\"");
        System.out.print(" ");
        for (int i = 0; i < length; i++) {
            System.out.print(ulchar);
        }
        System.out.println("");
    }

    @Override
    public Product createClone() {
        Product p = null;
        try {
            p = (Product)clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return p;
    }
}

Main
public class Main {

    public static void main(String[] args) {
    // write your code here
        Manager manager = new Manager();
        UnderlinePen upen = new UnderlinePen('~');
        MessageBox mbox = new MessageBox('*');
        MessageBox sbox = new MessageBox('/');
        manager.register("strong message", upen);
        manager.register("warning box", mbox);
        manager.register("salash box", sbox);


        Product p1 = manager.create("strong message");
        p1.use("Hello world.");
        Product p2 = manager.create("warning box");
        p2.use("Hello world.");
        Product p3 = manager.create("salash box");
        p3.use("Hello world.");

    }
}

你可能感兴趣的:(图解设计模式Prototype模式)