UML—设计模式

一。代理模式
为其他对象提供一种代理以控制这个对象。
1.实现如图代理模式的代码在这里插入图片描述
Public interface IRunner{
public void run();
}

public class Runner implements IRunner{
public void run(){
System.out.println(“运动员跑步”);
}
}

public class RunnerAgent implements IRunner{
private IRnner runner;
public RunnerAgent( IRunner _runner)
{
this.runner = _runner;
}

public void run
{
	Random rand = new Random();
	if(rand.nextBoolean)
	{
		system.out.println("跑");
		runner.run();
	}
	else
	sys("不跑");
}

}

public class Client{
public static main(String[] args)
//定义运动员,实现接入插口的类的方法
IRunner liu = new Runner;
//定义代理
IRunner agent = new RunnerAgent(liu);
//要求跑步
sys(“客人要运动员跑步”);
agent.run();
}

二.装饰模式
动态的给一些对象添加责任
1.实现下图代码
在这里插入图片描述
public class RnnerWithJet implements IRunner{
private IRunner runner;
public RnnerWithJet(IRunner _runner){
this.runner = _runner;
}
public void run(){
sys(“运动员增加了喷气装置”)
runner.run();
}
}

public class Client{
IRunner liu = new Runner();
liu = new RunnerWithJet(liu);
sys(“修饰过的运动员”);
liu.run();
}
在这里插入图片描述
public interface Swan{
public void fly();
public void cry();
public void desAppearance();
}

public class UglyDucking implements Swan(){
public void fly(){
sys(“不会飞”);
}
public void cry(){
sys(“嘎嘎”);
}
public void desAppearance(){
sys(“脏兮兮”);
}
}

public class Decorator implements Swan{
Swan swan;
public void Decrator(Swan _swan);{
this.swan = _swan;
}
public void cry(){
swan.cry();
}
public void fly(){
swan.fly;
}
public void desAppear(){
swan.desAppear();.
}
}

public class BeautyApprear extendsDecorator(){
public BeautyAppear(Swan _swan){
super(_swan);
}
@override
public void desApperance(){
sys(“外表纯白色”);
}
}

public class StrongBehavior{
public void StrongBehavior(Swan _swan){
super(_swan);
}
public void fly{
sys(“会飞了”);
}
}

public class Client{
public static void main(Sring[] main){
Swan duckling = new UglyDuckling();
duckling.desAppearance();
duckling.cry();
duckling.fly();
duckling = new BeautyAppear(duckling);
duckling = new StrongBehavior(duckling);
duckling.desAppearance();
duckling.cry();
duckling.fly();
}
}

四。适配器模式
在这里插入图片描述
public interface Duck{
public void cry();
public void desAppearance();
public void desBehavior();
}

public class Duckling implements Duck{
public void cry(){
sys(“嘎嘎”);
}
public void desAppearance(){
sys(“黄白相间”)
}
public void desBehavior(){
sys(“会游泳”);
}
}

public class WhiteSwan implements Swan{
public void cry(){
sys(“鹅鹅鹅”);
}
public void Appearance(){
sys(“纯白色”);
}
public void fly(){
sys(“会飞”);
}
}

public class UglyDuckling extends WhiteSwan implements Duck{ public void fly(){ super.fly(); } public void desBehavior(){ super.cry(); sys(“会游泳”); } public void desApperance(){ super.desApperance(); } } public class Client{ public static void main(String[] main){ Duck duck=new Duckling(); duck.cry(); duck.desAppearance(); duck.desBehavior(); Duck ugly=new UglyDuckling(); ugly.cry(); ugly.desAppearance(); ugly.desBehavior(); }