Java设计模式学习笔记(二)

单例模式
模式的定义与特点

单例模式的定义:指一个类只有一个实例,且该类能自行创建这个实例的模式。
特点:
1、单例类只有一个实例对象
2、该单例对象必须由单例类自行创建
3、单例类对外提供一个访问该单例的全局访问点

模式的结构与实现

将类的构造函数设为私有,外部无法调用该构造函数。同事该类自身必须定义一个静态私有实例,并向外提供一个静态的公有函数用于创建或获取该静态私有实例。

模式的结构:单例类和访问类

模式的实现:单例模式有两种
(1)懒汉式单例:该模式的特点是类加载时没有生成单例,只有当第一次调用get方法时才创建这个单例。

public class LazySingleton{
	private static volatile LazySingleton instance = null;
	private LazySingleton() {}
	public static synchronized LazySingleton getInstance() {
		if(instance == null) {
			instance = new LazySingleton();
		}
		return instance;
	}
}

(2)饿汉式单例:该模式的特点是类一旦加载就会创建一个单例,保证在调用get方法前单例已经存在。

public class HungrySingleton{
	private static final HungrySingleton instance = new HungrySingleton();
	private HungrySingleton() {}
	public static  HungrySingleton getInstance() {
		return instance;
	}
}
模式的应用实例

【1】懒汉式单例

package create.singleton;

//懒汉式单例
public class SingletonLazy {
	
	public static void main(String[] args) {
		President zt1 = President.getInstance();
		zt1.getName();
		President zt2 = President.getInstance();
		zt2.getName();
		if(zt1 == zt2) {
			System.out.println("他们是同一个人");
		}else {
			System.out.println("他们不是同一个人");
		}
	}
}

class President{
	
	//保证instance在所以线程中同步
	private static volatile President instance=null; 
	//private避免类在外部被实例化
	private President() {
		System.out.println("产生一个总统!");
	}
	//在getInstance方法加上同步
	public static synchronized President getInstance() {
		if(instance == null) {
			instance = new President();
		}else {
			System.out.println("已经有一个总统,不能产生新总统!");
		}
		return instance;
	}
	
	public void getName() {
		System.out.println("我是总统:XXXX");
	}
}

【2】饿汉式单例

package create.singleton;

import java.awt.*;
import javax.swing.*;

//饿汉式单例模式
public class SingletonEager {
	
	public static void main(String[] args) {
		JFrame jf = new JFrame("饿汉单例模式测试");
		jf.setLayout(new GridLayout(1,2));
		Container contentPane = jf.getContentPane();
		Bueaty obj1 = Bueaty.getInstance();
		contentPane.add(obj1);
		Bueaty obj2 = Bueaty.getInstance();
		contentPane.add(obj2);
		if(obj1 == obj2) {
			System.out.println("她们是同一个人");
		}else {
			System.out.println("她们不是同一个人");
		}
		jf.pack();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}

//单例类
class Bueaty extends JPanel{
	private static Bueaty instance = new Bueaty();
	private Bueaty() {
		JLabel ll = new JLabel(new ImageIcon("src/123.jpg"));
		this.add(ll);
	}
	public static Bueaty getInstance() {
		return instance;
	}
}
应用场景

(1)某类只要求生成一个对象
(2)当对象需要被共享的场合。单例模式只允许创建一个对象,共享该对象可以节省内存,并加快对象的访问速度。如Web中的配置对象、数据库的连接池等。
(3)当某类需要频繁实例化,而创建的对象又频繁被销毁时,如多线程的线程池,网络连接池等。

原型模式
模式的定义与特点

用一个已经创建的实例作为原型,通过复制该原型对象来创建一个和原型相同或相似的新对象。用这种方式创建对象非常高效,根本无须知道对象创建的细节。

模式的结构与实现

使用Java提供的clone()方法
1、模式的结构
(1)抽象原型类:规定了具体原型对象必须实现的接口。
(2)具体原型类:实现抽象原型类的clone()方法,它时可被复制的对象。
(3)访问类:使用具体原型类中的clone()方法来复制新的对象
2、模式的实现
原型模式的克隆分为浅克隆和深克隆,Java中的Object类提供了浅克隆的clone()方法,具体原型类只要实现Cloneable接口就可实现对象的浅克隆,这里的Cloneable接口就是抽象原型类。

package create.prototype;

//具体原型类
class Realizetype implements Cloneable{
	Realizetype(){
		System.out.println("具体原型创建成功!");
	}
	public Object clone() throws CloneNotSupportedException{
		System.out.println("具体原型复制成功!");
		return (Realizetype) super.clone();
	}
}
//原型模式的测试类
public class PrototypeTest {

	public static void main(String[] args) throws CloneNotSupportedException {
		Realizetype obj1 = new Realizetype();
		Realizetype obj2 = (Realizetype) obj1.clone();
		System.out.println("obj1==obj2 ?" + (obj1==obj2));
	}
}
模式的应用实例

【1】原型模式复制人物

package create.prototype;

import java.awt.*;
import javax.swing.*;

class CarToon extends JPanel implements Cloneable{
	//private static final long serialVersionUID = 5543049531872119328L;
	public CarToon() {
		JLabel l1 = new JLabel(new ImageIcon("src/timg.jpg"));
		this.add(l1);
	}
	public Object clone() {
		CarToon c = null;
		try {
			c = (CarToon)super.clone();
		}catch(CloneNotSupportedException e) {
			System.out.println("复制失败!");
		}
		return c;
	}
}

public class ProtoTypeCartoon {
	public static void main(String[] args) {
		JFrame jf = new JFrame("原型模式测试");
		jf.setLayout(new GridLayout(1, 2));
		Container contenPane = jf.getContentPane();
		CarToon obj1 = new CarToon();
		contenPane.add(obj1);
		CarToon obj2 = (CarToon)obj1.clone();
		contenPane.add(obj2);
		jf.pack();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}

【2】原型模式复制奖状

package create.prototype;

public class ProtoTypeCitation {

	public static void main(String[] args) throws CloneNotSupportedException {
		Citation obj1 = new Citation("小白","XXXXX","XXXXX");
		obj1.display();
		Citation obj2 = (Citation)obj1.clone();
		obj2.setName("小红");
		obj2.display();
	}
}

class Citation implements Cloneable{
	String name;
	String info;
	String college;
	Citation(String name,String info,String college){
		this.name = name;
		this.info = info;
		this.college = college;
		System.out.println("奖状创建成功!");
	}
	void setName(String name) {
		this.name = name;
	}
	String getName() {
		return (this.name);
	}
	void display() {
		System.out.println(name+":"+info+":"+college);
	}
	public Object clone() throws CloneNotSupportedException {
		System.out.println("奖状复制成功!");
		return (Citation)super.clone();
	}
}
应用场景

(1)对象之间相同或相似,即只是个别的几个属性不同的时候。
(2)对象的创建过程比较麻烦,但复制比较简单的时候。

模式的扩展

原型模式可扩展为带原型管理器的原型模式,它在原型模式的基础上增加了一个原型管理器PrototypeManager类。该类用HashMap保存多个复制的原型,Client类可以通过管理器get()方法从中获取复制的原型。

package create.prototype;

import java.util.HashMap;
import java.util.Scanner;

interface Shape extends Cloneable{
	public Object clone();//复制
	public void countArea();//计算面积
}
class Circle implements Shape{

	public Object clone() {
		Circle c= null;
		try {
			c = (Circle)super.clone();
		}catch(CloneNotSupportedException e) {
			System.out.println("复制园失败!");
		}
		return c;
	}
	public void countArea() {
		int r = 0;
		System.out.println("这是一个园,请输入圆的半径:");
		Scanner input = new Scanner(System.in);
		r = input.nextInt();
		System.out.println("园的面积="+3.1415*r*r+"\n");
	}
}
class Square implements Shape{

	public Object clone() {
		Square s = null;
		try {
			s = (Square)super.clone();
		}catch(CloneNotSupportedException e) {
			System.out.println("复制正方形失败!");
		}
		return s;
	}
	public void countArea() {
		int a = 0;
		System.out.println("这是一个正方形,请输入正方形的边长:");
		Scanner input = new Scanner(System.in);
		a = input.nextInt();
		System.out.println("正方形的面积="+a*a+"\n");
	}
}
class ProtoTypeManager{
	private HashMap<String,Shape> ht = new HashMap<String,Shape>();
	public ProtoTypeManager() {
		ht.put("Circle", new Circle());
		ht.put("Square", new Square());
	}
	public void addshape(String key,Shape obj) {
		ht.put(key, obj);
	}
	public Shape getShape(String key) {
		Shape temp = ht.get(key);
		return (Shape) temp.clone();
	}
}
public class ProtoTypeShape {

	public static void main(String[] args) {
		ProtoTypeManager pm = new ProtoTypeManager();
		Shape obj1 = (Circle)pm.getShape("Circle");
		obj1.countArea();
		Shape obj2 = (Square)pm.getShape("Square");
		obj2.countArea();
	}
}

本篇为读书笔记,概念和代码均出自书籍《软件设计模式(Java版)》作者:程细柱,人民邮电出版社。请自觉支持正版!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值