常用设计模式举例,观察者模式,装饰模式,工厂模式,单列模式---Head Frist 设计模式源码

1.概念

设计原则:要依赖抽象,不要依赖具体类。针对接口编程。

策略模式:定义算法族,分别封装起来,让它们之间可以互相替换。此模式让算法的变化独立于使用算法的客户。

观察者模式:定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。

装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。

工厂模式 :通过让子类决定该创建的对象是什么,来达到将对象创建的过程封装的目的。

工厂方法模式:定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。

抽象工厂模式:提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。

单例设计模式:确保一个类只有一个实例,并提供一个局部访问点。

命令模式:将请求封装成对象,,以便使用不同的请求。队列或者日志来参数化其它对象,命令模式也支持课撤销的操作。

2.举例和源代码

观察者模式:

//实现气象站
//1,建立接口开始
public interface Subject{
	public void registerObserver(Observer o);//前面两个方法都需要一个观察者作为变量,该观察者是用来注册或被删除的
	public void removeObserver(Observer o);
	public void notfiyObserver();//当主题状态改变时,这个方法会被调用,以通知所有的观察者
}
public interface Observer{
	public void update(float temp,float humidity,float pressure);//当气象观测值改变时主题会把这些状态值当作方法的参数,传给观察者。
	//所有的观察者都必须实现update()方法,以实现观察者接口
}
public interface DisplayElement{
	public void display();//DisplayElement接口只包含一个方法,也就是display。显示时,调用此方法。
}
//实现接口
public class WeatherData implements Subject{//WeatherData现在实现了Subject接口
	private ArrayList observers;
	private float temperature;
	private float humidity;
	private float pressure;
	public WeatherData(){
		observer=new ArrayList();//记录观察者
	}
	public void registerObserver(Observer o){//当注册观察者时,我们只要把它加到ArrayList的后面即可
	observers.add(o);
		
	}
	public void removeObserver(Observer o){
		int i=observers.indexOf(o);
		if(i>=0){
			observers.remove(i);
		}
	}
	public void notfiyObservers(){//我们把状态告诉每一个观察者。因为都实现了update
		for(int i=0;i<observers.size();i++){
			Observer observer=(Observer)observers.get(i);
			observer.update(temperature,humidity,pressure);
		}
	}
	public void measurementsChanged(){
		//当从气象站得到更新观测值是,我们通知观察者
		notfiyObservers();
	}
	public void setMeasurements(float temperature,float humidity,float pressure){
		this.temperature=temperature;
		this.humidity=humidity;
		this.pressure=pressure;
		measurementsChanged();
	}
	//WeatherData的其它方法
}
//建立布告板:目前状况、统计、预测
public class CurrentConditionDisplay implements Observer,DisplayElement{
	private float temperature;
	private float humidity;
	private Subject weatherData;
	public CurrentConditionDisplay(Subject weatherData){//构造器需要weatherData对象作为政策从之后
	this.temperature=temperature;
	this.humidity=humidity;
	display();
		
	}
	public void display(){
		System.out.println(".........");
	}
}

//测试程序
public class WeatherDataTest{
	public static void main(String[] args){
		WeatherData weatherData=new WeatherData();//首先建立对象
		CurrentConditionDisplay currentDisplay=new CurrentConditionDisplay(weatherData);
		StatisticsDisplay statisticDisplay=new StatisticsDisplay(weatherData);
		ForecastDisplay forecastDisplay=new ForecastDisplay(weatherData);
		
		weatherData.setMeasurements(80,65,30.4f);
	}
}
工厂模式:

//建造原料工厂
/*
现在,我们要建造一个工厂来生产原料;这个工厂将负责创建原料家族中的每一种原料。也就是说,工厂将需要生产面团、
酱料、等待会儿,你就会知道如何处理各个区域的差异了。
开始先为工厂定义一个接口,这个接口负责创建所有的原料。
*/ 
public interface PizzaIngredientFactory{
	public Dough createDough();
	public Sauce createSauce();
	public Veggies[] createVeggies();
	public Chese createCheese();
	public Pepperoni createPepperoni();
	public Clams createClam();
}
/*
要做的事:1.为每个区域建造一个工厂,你需要创建一个继承自PizzaIngredientFactory的子类来实现每一个创建方法。
2.实现一组原料类供应工厂使用
3.然后你仍然需要将这一切组织起来,将新的原料工厂整合进旧的PizzaStore代码中
*/
public class NYPizzIngredientFactory implements PizzaIngredientFactory{
	public Dough createDough(){
		return new ThinCrustDough();
	}
	public Sauce createSauce(){
		return new MarinaraSauce();
		
	}
	public Chese createCheese(){
		return new ReggainoCheese();
	}
	public Veggies[] createVeggies(){
		Veggies veggies[] ={new Garlic(),new Onion(),new Mushroom(),new RedPepper()};
		return veggies;
	}
	public Pepperoni createPepperoni(){
		return new SlicesPepperoni();
	}
	public Clams createClam(){
		return new FreshClams();
	}
}
//重做披萨
public abstract class Pizza{
	String name;
	Dough dough;
	Sauce sauce;
	Veggies veggies[];
	Chese cheses;
	Pepperoni pepperoni;
	Clams clam;
	abstract void perpare();
	void bake(){
		system.out.println("披萨");
	}
	void setName(String name){
		this.name=name;
	}
	String getName(){
		return name;
	}
}
public class ChesePizza extends Pizza{
	PizzaIngredientFactory ingredientFactory;
	public ChesePizza (PizzaIngredientFactory ingredientFactory){
		this.ingredientFactory=ingredientFactory;
	}
	void perpare(){
		dough=ingredientFactory.createDough();
		sauce=ingredientFactory.createSauce();
		cheses=ingredientFactory.createCheese();
	}
}
//哈利披萨
public class ClamPizza extends Pizza{
	PizzaIngredientFactory ingredientFactory;
	public ClamPizza(PizzaIngredientFactory ingredientFactory){//其实这个就像依赖注入一样。
		this.ingredientFactory=ingredientFactory;
	}
	void perpare(){
		dough=ingredientFactory.createDough();
		sauce=ingredientFactory.createSauce();
		cheses=ingredientFactory.createCheese();
		clam=ingredientFactory.createClam();
	}
}
装饰模式:

public class SwingObserverExample{
	
}
public abstract class Beverage{//装饰着类
	String description="Unkonwn Beverage";
	public String getDescription(){
		return description;
	}
	public abstract double cost();
	
}
public abstract class CondimentDecorator extends Beverage{
	public abstract String getDescription();//所有的装饰者都必须重新实现getDescription()方法 
	
}
public class Espresso extends Beverage{//一种饮料
	public Espresso(){
		description="Espresso";//为了要设置饮料的描述,我们写了一个构造器。记住description实例变量继承自Beverage.
		
	}
	public double cost(){
		return 1.99;//最后设置价钱
	}
	
}
public class HouseBlend extends Beverage{
	public HouseBlend(){
		description="House Blend Coffe";
		
	}
	public double cost(){
		return 0.89;
	}
}
public class Mocha extends CondimentDecorator{
	Beverage beverage;
	public Mocha (Beverage beverage){
		this.beverage=beverage;
	}
	public String getDescription(){
		return beverage.getDescription()+",Mocha";
	}
	public double cost(){
		return 20+beverage.cost();//
	}
}
//测试类
public class StardbuzzCoffee{
	public static void main(String[] args){
		Beverage beverage =new Espresso();
		Beverage beverage2 =new DarkRoast();
	}
}

单列模式

public  class Singleton{
	private static Singleton uniqueInstance;
	//这里是其它的有用实例化变量
	private Singleton(){}//把构造器声明为私有的。
	private static Singleton getInstance(){
		if(uniqueInstance == null){
			uniqueInstance = new Singleton();
		}
		return uniqueInstance;
			
	}
	//这里有其它的有用的方法
	
	
}
//处理多线程
/*
只要把getInstance()变成{synchronized}方法,多线程的问题就可以解决
*/
public class Singleton{
	private static Singleton uniqueInstance;
	//其它有用的实例化变量
	private Singleton(){}
	public static synchronized Singleton getInstance(){
		if(uniqueInstance == null){
			uniqueInstance= new Singleton();
		}
		return uniqueInstance;
	}
}
/*
上面可能出现延迟加载的问题,性能低
*/
public class Singleton{
	private static Singleton uniqueInstance = new Singleton();//保证线程的安全
	private Singleton(){}
	public static Singleton getInstance(){
		return uniqueInstance;//已经有实例了,直接使用它
	}
}
/*
第二种方法。利用双重检查加锁
*/
public class Singleton{
	private volatile static Singleton uniqueInstance;//volatile关键字确保,当uniqueInstance变量被初始化成,多个线程正确处理变量
	private Singleton(){
		
	}
	public static Singleton getInstance(){
		if(uniqueInstance == null){
			synchronized(Singleton.class){
				if( uniqueInstance == null){
					uniqueInstance = new Singleton();
				}
			}
		}
		return uniqueInstance;
	}
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值