多例设计模式

本文介绍了多例设计模式的概念,将其比喻为多个单例模式的组合。详细讲解了如何通过实例复制创建多个相同的对象,并提供了代码示例,包括Product接口、Manager管理类以及具体的实现类MessageBox和UnderlinePen。在MainTest类中进行了测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、什么是多例模式?

​ 多例模式是可以理解为"多个单例模式",通过一个实例复制出多个一模一样的实例。

2、代码

2.1、Product接口,所有的产品都实现它

public interface Product extends Cloneable {
	void use(String s);
	Product createClone();
}

2.2、Manager类,管理实例的类

public class Manager {

	private HashMap showcase = new HashMap();
	
	public void register(String name,Product product) {
		showcase.put(name, product);
		
	}
	
	public Product create(String protoname) {
		Product product = (Product)showcase.get(protoname);
		return product.createClone();
	}
}

2.3、MessageBox类,实现了Product接口,具体处理use方法和clone方法

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("");
	}

    //通过Object的克隆方法实现复制
	@Override
	public Product createClone() {
		Product product = null;
		try {
			product = (Product) clone();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return product;
	}

}

2.4、UnderlinePen类,同2.3

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 product = null;
		try {
			product = (Product) clone();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return product;
	}

}

2.5、MainTest类,测试用

public class MainTest {
	
	public static void main(String[] args) {
		//准备
		Manager manager = new Manager();
		UnderlinePen underlinePen = new UnderlinePen('~');
		MessageBox box1 = new MessageBox('*');
		MessageBox box2 = new MessageBox('/');
		manager.register("strong message", underlinePen);
		manager.register("warning box", box1);
		manager.register("slash box", box2);
		
		//生成
		Product p1 = manager.create("strong message");
		p1.use("Hello world!");
		Product p2 = manager.create("warning box");
		p2.use("Hello world!");
		Product p3 = manager.create("slash box");
		p3.use("Hello world!");
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值