4种简单设计模式

常用的设计模式:
单例设计模式
模板设计模式
工厂设计模式
代理设计模式

1.单例设计模式

单例设计模式:就是无论我们如何创建对象,你得到的都是同一个对象。
思路:
1.私有化构造方法
2.在当前类中定义一个本类类型的静态属性
3.编写静态块,对本类类型的静态属性实例化对象
4.编写一个静态的方法,向外界提供私有化的静态属性

public class Single(){
private static Single single;
static{
single=new Single();
}
private Single(){

}
public static Single getSingle(){
	return single;
}

}

2.模板设计模式

相当于父类与子类的关系

3.工厂设计模式

①定义一个车的父类,有跑的功能
public abstract class Car
{
public abstract void Run();
}
②定义两个子类,一个奔驰,一个大众
public class BMWCar implements Car
{
public override void Run()
{
Console.WriteLine(“宝马轿车在行驶!”);
}
}
public class BenzCar implements Car
{
public override void Run()
{
Console.WriteLine(“奔驰轿车在行驶!”);
}
}
③定义工厂类
public class Factory
{
public static Car CreateCar(string carType)
{
Car car = null;
switch (carType)
{
case “BMW”:
car = new BMWCar();
break;
case “Benz”:
car = new BenzCar();
break;
}
return car;
}
}
④main方法中
Car car = Factory.CreateCar(“Benz”);
car.Run();

4.代理设计模式

①假的代理
public class Fake {

public Real real;
public Fake(Real real){
	this.real=real;
}
public void net(){
	real.net();
}

}
②真的代理
public class Real {

public void net(){
	System.out.println("开始上网");
}

}
③main方法
public class Test {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	Real real=new Real();
	Fake fake=new Fake(real);
	fake.net();
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值