设计模式之建立对象实例--singleton/prototype

五、singleton唯一的对象实例

public class Singleton {
    private static Singleton singleton=new Singleton();

    private Singleton() {
        System.out.println("产生对象实例");
    }
    public static Singleton getInstance(){
        return singleton;
    }
}

六、prototype原型、复制建立对象实例

 

public interface Product extends Cloneable{
    void use(String s);
    Product createClone();
}
public class Manager {
   private Hashtable products= new Hashtable();
   public void register(String name,Product product){
       products.put(name,product);
   }
   public Product create(String protoname){
       Product product = (Product) products.get(protoname);
       return product.createClone();
   }

}
public class MessageBox implements Product {
    private char messageBoxChar;

    public MessageBox(char messageBoxChar) {
        this.messageBoxChar = messageBoxChar;
    }

    @Override
    public void use(String s) {
        System.out.println(messageBoxChar+""+s+""+messageBoxChar);
    }

    @Override
    public Product createClone() {
        Product product=null;
        try {
            product = (Product) clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return product;
    }
}
public class UnderLinePen implements Product {
    private char charPen;

    public UnderLinePen(char charPen) {
        this.charPen = charPen;
    }

    @Override
    public void use(String s) {
        int length = s.getBytes().length;
        System.out.println("*"+s+"*");
        for (int i = 0; i < length+2; i++) {
            System.out.print(charPen);
        }
        System.out.println();
    }

    @Override
    public Product createClone() {
        Product product=null;
        try {
            product=(Product) clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return product;
    }
}
public class Test {
    public static void main(String[] args) {
        Manager manager = new Manager();
        MessageBox messageBox = new MessageBox('$');
        UnderLinePen underLinePen = new UnderLinePen('@');
        manager.register("messageBox",messageBox);
        manager.register("underLinePen",underLinePen);

        Product underLinePenProduct = manager.create("underLinePen");
        Product messageBoxProduct = manager.create("messageBox");
        underLinePenProduct.use("joanna");
        System.out.println("underLinePen输出完成");
        messageBoxProduct.use("zhouzhou");
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值