尚硅谷_韩顺平_图解Java设计模式 https://pan.baidu.com/s/1u382gJfOmK_X7Qo6VbFjsQ 提取码: 28ei
学校的Java设计模式ppt https://pan.baidu.com/s/1bVwz5ALf7UsRMJlsEYzjDg 提取码: 7knw
我们在实例化对象的时候通常需要用 new 关键字, 这样耦合度比较高,于是有了工厂模式,将new一个对象放到工厂中,用工厂new一个对象再给我返回
public class SimpleFactory {
//更加 orderType 返回对应的 Pizza 对象
public Pizza createPizza(String orderType) {
Pizza pizza = null;
System.out.println("使用简单工厂模式");
if (orderType.equals("greek")) {
pizza = new GreekPizza();
pizza.setName(" 希腊披萨 ");
} else if (orderType.equals("cheese")) {
pizza = new CheesePizza();
pizza.setName(" 奶酪披萨 ");
} else if (orderType.equals("pepper")) {
pizza = new PepperPizza();
pizza.setName("胡椒披萨");
}
return pizza;
}
public class OrderPizza {
//定义一个简单工厂对象SimpleFactory simpleFactory; Pizza pizza = null;
SimpleFactory simpleFactory;
Pizza pizza = null;
//构造器
public OrderPizza(SimpleFactory simpleFactory) {
setFactory(simpleFactory);
}
public void setFactory(SimpleFactory simpleFactory) {
String orderType = ""; //用户输入的
this.simpleFactory = simpleFactory; //设置简单工厂对象
orderType = getType();
pizza = this.simpleFactory.createPizza(orderType);
//输出 pizza
if(pizza != null) { //订购成功
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
} else {
System.out.println(" 订购披萨失败 "); break;
}
}
简单工厂模式实际上就是面向过程=>面向对象的形式,我们把过程封装在工厂容器中,别人看不到,因为做披萨的过程不需要别人知道,别人只管拿到披萨吃就行了。
返回顶部
工厂方法模式是简单工厂模式的升级版,上面的模式我们会发现一个问题:就是制作披萨的过程是相同的,只是披萨的类型不同,创建多个披萨就要写多个一样的方法,所以需要用到新的方式:创建一个抽象类,抽取共有的方法,所有的披萨继承这个抽象类,制作过程都一样,只需要在其中加入自己独有的方法就行。
public abstract class Gj19IMGReader {
public abstract void read();
}
public class Gj19JPGReader extends Gj19IMGReader {
@Override
public void read() {
System.out.println("读jpg");
}
}
public class Gj19GIFReader extends Gj19IMGReader {
@Override
public void read() {
System.out.println("读gif");
}
}
public abstract class Gj19IMGReaderFactory {
public abstract void getGj19IMGReader(Gj19IMGReader reader);
}
public class Gj19JPGReaderFactory extends Gj19IMGReaderFactory{
@Override
public void getGj19IMGReader(Gj19IMGReader reader) {
reader.read();
}
}
public class Gj19GIFReaderFactory extends Gj19IMGReaderFactory {
@Override
public void getGj19IMGReader(Gj19IMGReader reader) {
reader.read();
}
}
public class Application {
public static void main(String[] args) {
Gj19IMGReaderFactory factory = new Gj19JPGReaderFactory();
Gj19IMGReader reader = new Gj19JPGReader();
factory.getGj19IMGReader(reader);
factory = new Gj19JPGReaderFactory();
reader = new Gj19GIFReader();
factory.getGj19IMGReader(reader);
}
}
返回顶部
抽象工厂模式是工厂方法模式的升级版,抽象工厂模式中我们可以定义实现不止一个接口,一个工厂也可以生成不止一个产品类
相当于我要做披萨的同时做面包 ,假设两种用到的原材料都一样,所以我们可以将披萨和面包的原材料提取出来,实现不同的口味就行。
public abstract class CPU {
public abstract void show_CPU();
}
public class MacCPU extends CPU {
@Override
public void show_CPU() {
System.out.println("MacCPU");
}
}
public class PcCPU extends CPU {
@Override
public void show_CPU() {
System.out.println("PcCPU");
}
}
public abstract class RAM {
public abstract void show_RAM();
}
public class MacRAM extends RAM {
@Override
public void show_RAM() {
System.out.println("MacRAM");
}
}
public class PcRAM extends RAM {
@Override
public void show_RAM() {
System.out.println("PcRAM");
}
}
public abstract class AbstractFactory {
public abstract void createRAM();
public abstract void createCPU();
}
public class MacFactory extends AbstractFactory {
@Override
public void createRAM() {
new MacRAM().show_RAM();
}
@Override
public void createCPU() {
new MacCPU().show_CPU();
}
}
public class PcFactory extends AbstractFactory {
@Override
public void createRAM() {
new PcRAM().show_RAM();
}
@Override
public void createCPU() {
new PcCPU().show_CPU();
}
}
public class Application {
public static void main(String[] args) {
AbstractFactory factory = new PcFactory();
factory.createRAM();
factory.createCPU();
factory = new MacFactory();
factory.createRAM();
factory.createCPU();
}
}
返回顶部
传统建房子:打桩、砌墙、封顶,房子有各种各样的,比如普通房,高楼,别墅,各种房子的过程虽然一样,但是要求不相同的
传统建房子设计的程序结构,过于简单,没有设计缓存层对象,程序的扩展和维护不好. 也就是说,这种设计方案,把产品(即:房子) 和 创建产品的过程(即:建房子流程) 封装在一起,耦合性增强了。
public class Car {
private String faDongJi;
private String bianSuXiang;
private String diPan;
public String getFaDongJi() {
return faDongJi;
}
public void setFaDongJi(String faDongJi) {
this.faDongJi = faDongJi;
}
public String getBianSuXiang() {
return bianSuXiang;
}
public void setBianSuXiang(String bianSuXiang) {
this.bianSuXiang = bianSuXiang;
}
public String getDiPan() {
return diPan;
}
public void setDiPan(String diPan) {
this.diPan = diPan;
}
@Override
public String toString() {
return "Car{" +
"faDongJi='" + faDongJi + '\'' +
", bianSuXiang='" + bianSuXiang + '\'' +
", diPan='" + diPan + '\'' +
'}';
}
}
public abstract class CarBuilder {
protected Car car = new Car();
public abstract void buildFaDongJi();
public abstract void buildBianSuXiang();
public abstract void buildDiPan();
public Car build(){
return car;
}
}
public class Director {
CarBuilder carBuilder;
public Director(CarBuilder carBuilder) {
this.carBuilder = carBuilder;
}
public Car constructCar(){
carBuilder.buildFaDongJi();
carBuilder.buildBianSuXiang();
carBuilder.buildDiPan();
return carBuilder.build();
}
}
public class BenChi extends CarBuilder {
@Override
public void buildFaDongJi() {
car.setFaDongJi("奔驰的发动机");
}
@Override
public void buildBianSuXiang() {
car.setBianSuXiang("奔驰的变速箱");
}
@Override
public void buildDiPan() {
car.setDiPan("奔驰的底盘");
}
}
public class BaoMa extends CarBuilder {
@Override
public void buildFaDongJi() {
car.setFaDongJi("宝马的发动机");
}
@Override
public void buildBianSuXiang() {
car.setBianSuXiang("宝马的变速箱");
}
@Override
public void buildDiPan() {
car.setDiPan("宝马的底盘");
}
}
public class AoDi extends CarBuilder {
@Override
public void buildFaDongJi() {
car.setFaDongJi("奥迪的发动机");
}
@Override
public void buildBianSuXiang() {
car.setBianSuXiang("奥迪的变速箱");
}
@Override
public void buildDiPan() {
car.setDiPan("奥迪的底盘");
}
}
public class Application {
public static void main(String[] args) {
BaoMa builder1 = new BaoMa();
Director director1 = new Director(builder1);
System.out.println(director1.constructCar());
BenChi builder2 = new BenChi();
Director director2 = new Director(builder2);
System.out.println(director2.constructCar());
AoDi builder3 = new AoDi();
Director director3 = new Director(builder3);
System.out.println(director3.constructCar());
}
}
返回顶部
现在对不同手机类型的不同品牌实现操作编程(比如:开机、关机、上网,打电话等)
如果我们增加手机的样式,就需要增加各个品牌手机的类,同样如果我们增加一个手机品牌,也要在各个手机样式类下增加。
这违反了单一职责原则,当我们增加手机样式时,要同时增加所有品牌的手机,这样增加了代码维护成本
桥接模式可以解决这一问题。
public abstract class Shape {
DrawApi drawApi;
public Shape(DrawApi drawApi) {
this.drawApi = drawApi;
}
public abstract String draw() ;
}
public class Circle extends Shape {
private int radius;
public Circle(DrawApi drawApi, int radius) {
super(drawApi);
this.radius = radius;
}
@Override
public String draw() {
drawApi.drawCircle();
return "半径为"+(radius*2*3.14);
}
}
public interface DrawApi {
void drawCircle();
}
public class GreenCircle implements DrawApi {
@Override
public void drawCircle() {
System.out.println("绿色圆");
}
}
public class RedCircle implements DrawApi {
@Override
public void drawCircle() {
System.out.println("红色圆");
}
}
public class Application {
public static void main(String[] args) {
DrawApi draw1 = new RedCircle();
Circle circle1 = new Circle(draw1,3);
System.out.println(circle1.draw());
DrawApi draw2 = new GreenCircle();
Circle circle2 = new Circle(draw2,5);
System.out.println(circle2.draw());
}
}
返回顶部
public abstract class File {
String name;
public File(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void display();
}
public class Folder extends File{
private List<File> files;
public Folder(String name){
super(name);
files = new ArrayList<File>();
}
/**
* 浏览文件夹中的文件
*/
public void display() {
for(File file : files){
file.display();
}
}
/**
* @desc 向文件夹中添加文件
* @param file
* @return void
*/
public void add(File file){
files.add(file);
}
/**
* @desc 从文件夹中删除文件
* @param file
* @return void
*/
public void remove(File file){
files.remove(file);
}
}
public class ImageFile extends File{
public ImageFile(String name) {
super(name);
}
public void display() {
System.out.println("这是图像文件,文件名:" + super.getName());
}
}
public class TextFile extends File{
public TextFile(String name) {
super(name);
}
public void display() {
System.out.println("这是文本文件,文件名:" + super.getName());
}
}
public class VideoFile extends File{
public VideoFile(String name) {
super(name);
}
public void display() {
System.out.println("这是影像文件,文件名:" + super.getName());
}
}
public class Application {
public static void main(String[] args) {
//总文件夹
Folder jwh = new Folder("总文件夹");
//向总文件夹中放入三个文件:1.txt、2.jpg、3.文件夹
TextFile text_1= new TextFile("1.txt");
ImageFile image_1 = new ImageFile("2.jpg");
Folder folder_1 = new Folder("1.文件夹");
jwh.add(text_1);
jwh.add(image_1);
jwh.add(folder_1);
//向1.文件夹中添加文件:1.1.txt、1.1.jpg、1.1.mp4
TextFile text_1_1 = new TextFile("1.1.txt");
ImageFile image_1_1 = new ImageFile("1.1.jpg");
VideoFile mp4_1_1 = new VideoFile("1.1.mp4");
folder_1.add(text_1_1);
folder_1.add(image_1_1);
folder_1.add(mp4_1_1);
System.out.println("删除前:");
//遍历1.文件夹
folder_1.display();
//将1.1.txt删除
folder_1.remove(text_1_1);
System.out.println("删除后:");
folder_1.display();
}
}
返回顶部
public interface Avi {
void playAvi();
}
public interface Mp4 {
void playMp4();
}
public class VideoPlayer implements Mp4{
@Override
public void playMp4() {
System.out.println("播放Mp4格式的视频");
}
}
public class FormatFactory extends VideoPlayer implements Avi{
@Override
public void playAvi() {
//转换成MP4格式的视频
super.playMp4();
}
}
public class Application {
public static void main(String[] args) {
Mp4 mp4=new VideoPlayer();
mp4.playMp4();
Avi avi=new FormatFactory();
avi.playAvi();
}
}
返回顶部
public abstract class Phone {
public abstract void call();
}
public class SimplePhone extends Phone{
public SimplePhone() {
}
public void call(){
System.out.println("叮铃铃");
}
}
public class PhoneDecorator extends Phone {
private Phone phone;
public PhoneDecorator(Phone phone) {
if (phone != null) {
this.phone = phone;
} else {
this.phone = new SimplePhone();
}
}
@Override
public void call() {
phone.call();
}
}
public class JarPhone extends PhoneDecorator {
public JarPhone(Phone phone) {
super(phone);
}
public void call() {
super.call();
System.out.println("震动");
}
}
public class ComplexPhone extends PhoneDecorator {
public ComplexPhone(Phone phone) {
super(phone);
}
public void call() {
super.call();
System.out.println("灯光闪烁");
}
}
public class Application {
public static void main(String[] args) {
Phone p1 = new SimplePhone();
p1.call();
System.out.println("----");
Phone p2 = new JarPhone(p1);
p2.call();
System.out.println("----");
Phone p3 = new ComplexPhone(p2);
p3.call();
}
}
返回顶部
public interface VipStatus {
void pays();
}
public class YellowStatus implements VipStatus {
private double money;
public YellowStatus(double money) {
this.money = money * 0.8;
}
@Override
public void pays() {
System.out.println("您是黄金会员,消费了"+money+"元");
}
}
public class WhiteStatus implements VipStatus {
private double money;
public WhiteStatus(double money) {
this.money = money * 0.7;
}
@Override
public void pays() {
System.out.println("您是白金会员,消费了"+money+"元");
}
}
public class BlackStatus implements VipStatus {
private double money;
public BlackStatus(double money) {
this.money = money * 0.6;
}
@Override
public void pays() {
System.out.println("您是黑金会员,消费了"+money+"元");
}
}
public class Card {
VipStatus status;
public void showMessage(){
System.out.println("***********");
status.pays();
System.out.println("***********");
}
public void setState(VipStatus status){
this.status=status;
}
}
public class Application{
public static void main(String args[]) {
VipStatus status=new YellowStatus(1000);
Card card=new Card();
card.setState(status);
card.showMessage();
status=new WhiteStatus(1000);
card.setState(status);
card.showMessage();
status=new BlackStatus(1000);
card.setState(status);
card.showMessage();
}
}
返回顶部
代码:
public class Circle {
double radius;
double location;
public Circle(double radius, double location) {
this.radius = radius;
this.location = location;
}
public double getRadius() {
return radius;
}
public double getLocation() {
return location;
}
}
public interface Paint{
void printCircle(Circle circle);
}
//具体的绘制方式
public class ConcretePaint implements Paint {
//共享的部分,内部状态
private String color;
public ConcretePaint(String color) {
this.color = color;
}
@Override
public void printCircle(Circle circle) {
System.out.println("画一个:" + color + "的圆,半径为:" + circle.getRadius() + ",位置为:" + circle.getLocation());
}
}
//圆的工厂类,根据需要返回一个圆
public class FlyweightFactory {
//集合, 充当池的作用
private HashMap<String, ConcretePaint> pool = new HashMap<>();
//根据圆的颜色,返回一个圆, 如果没有就创建一个圆,并放入到池中,并返回
public Paint getPaintCategory(String color) {
if (!pool.containsKey(color)) {
pool.put(color, new ConcretePaint(color));
}
return pool.get(color);
}
//获取圆分类的总数
public int getPaintCount() {
return pool.size();
}
}
public class Application{
public static void main(String args[]) {
FlyweightFactory factory = new FlyweightFactory();
Paint paint1 = factory.getPaintCategory("红色");
paint1.printCircle(new Circle(5,5));
paint1.printCircle(new Circle(10,10));
System.out.println("*******************");
Paint paint2 = factory.getPaintCategory("黄色");
paint2.printCircle(new Circle(5,5));
paint2.printCircle(new Circle(10,10));
System.out.println("*******************");
Paint paint3 = factory.getPaintCategory("蓝色");
paint3.printCircle(new Circle(5,5));
paint3.printCircle(new Circle(10,10));
System.out.println("*******************");
System.out.println("圆的颜色分类共" + factory.getPaintCount() + "种");
}
}
结果:
画一个:红色的圆,半径为:5.0,位置为:5.0
画一个:红色的圆,半径为:10.0,位置为:10.0
*******************
画一个:黄色的圆,半径为:5.0,位置为:5.0
画一个:黄色的圆,半径为:10.0,位置为:10.0
*******************
画一个:蓝色的圆,半径为:5.0,位置为:5.0
画一个:蓝色的圆,半径为:10.0,位置为:10.0
*******************
圆的颜色分类共3种
返回顶部
//此类是Receiver,用来接收按键请求而打印不同技能
public class Skill {
public void skill_1(){
System.out.println("使用一技能");
}
public void skill_2(){
System.out.println("使用一技能");
}
public void skill_3(){
System.out.println("使用三技能");
}
}
//此类是Command,用来发起按键请求
public interface Key {
void execute();
}
//下面三个类是ConcreteCommand,用来实现具体的按键请求,即实现execute
public class KeyOne implements Key {
private Skill skill;
public KeyOne(Skill skill){
this.skill = skill;
}
public void execute() {
skill.skill_1();
}
}
public class KeyTwo implements Key {
private Skill skill;
public KeyTwo(Skill skill){
this.skill = skill;
}
public void execute() {
skill.skill_2();
}
}
public class KeyThree implements Key {
private Skill skill;
public KeyThree(Skill skill){
this.skill = skill;
}
public void execute() {
skill.skill_3();
}
}
//此类是Invoker,将三个键都存入集合中,再通过placeKeys直接调用三个按键方法
public class LanLinWang {
private List<Key> keyList = new ArrayList<>();
public void takeKey(Key key){
keyList.add(key);
}
public void placeKeys(){
for (Key key : keyList) {
key.execute();
}
keyList.clear();
}
}
//总结:将三个技能对应添加到按键中,再通过兰陵王将按键存入集合中,通过方法调用按键,也就能调用相应技能
public class Application {
public static void main(String[] args) {
Skill skill = new Skill();
KeyOne keyOne = new KeyOne(skill);
KeyTwo keyTwo = new KeyTwo(skill);
KeyThree keyThree = new KeyThree(skill);
LanLinWang lanLinWang= new LanLinWang();
lanLinWang.takeKey(keyOne);
lanLinWang.takeKey(keyTwo);
lanLinWang.takeKey(keyThree);
lanLinWang.placeKeys();
}
}
输出
使用一技能
使用一技能
使用三技能
返回顶部
//相当于Handler
public interface Measures {
void handleMeasure(int number);
void setNextMeasure(Measures measures);
}
//ConcreteHandler
public class LevelOne implements Measures {
private Measures measures;
//Request
public void handleMeasure(int number){
if(number>0 && number<=10)
System.out.println("启动一级隔离措施,病房隔离");
else{
if(measures !=null)
measures.handleMeasure(number);
}
}
public void setNextMeasure(Measures measures){
this.measures = measures;
}
}
//ConcreteHandler
public class LevelTwo implements Measures {
private Measures measures;
//Request
public void handleMeasure(int number){
if(number>10 && number<=100)
System.out.println("启动二级隔离措施,居家隔离");
else{
if(measures !=null)
measures.handleMeasure(number);
}
}
public void setNextMeasure(Measures measures){
this.measures = measures;
}
}
//ConcreteHandler
public class LevelThree implements Measures {
private Measures measures;
//Request
public void handleMeasure(int number){
if(number>100 && number<=1000)
System.out.println("启动三级隔离措施,方舱医院隔离");
else{
if(measures !=null)
measures.handleMeasure(number);
}
}
public void setNextMeasure(Measures measures){
this.measures = measures;
}
}
public class Application {
public static void main(String[] args) {
LevelOne l1 = new LevelOne();
LevelTwo l2 = new LevelTwo();
LevelThree l3 = new LevelThree();
//设置责任链,相当于不满足1就找2,不满足2就找3
l1.setNextMeasure(l2);
l2.setNextMeasure(l3);
l1.handleMeasure(5);
l1.handleMeasure(55);
l1.handleMeasure(555);
}
}
输出
启动一级隔离措施,病房隔离
启动二级隔离措施,居家隔离
启动三级隔离措施,方舱医院隔离
返回顶部
基本介绍
*注:本题最简单的方法可采用单个对象重复对其属性赋值(也就是重复传入不同的字符串)的方式达到重复存档读档的效果,但我采用更高级的集合形式,也就是可以存多个档,更与现实相符
//先定义一个备忘录对象用来保存历史事件,此类是备忘录模式最内部状态,即备忘录里面的应该保存的属性
public class Memento {
private String historical_event;
//有参构造器
public Memento(String historical_event) {
this.historical_event = historical_event;
}
public String getHistorical_event() {
return historical_event;
}
public void setHistorical_event(String historical_event) {
this.historical_event = historical_event;
}
}
//游戏角色,用来创建备忘录对象以及展示备忘录对象
public class GameRole {
private String historical_event;
//创建 Memento ,即根据当前的状态得到 Memento
public Memento createMemento() {
return new Memento(historical_event);
}
//从备忘录对象,恢复 GameRole 的状态
public void recoverGameRoleFromMemento(Memento memento) {
this.historical_event = memento.getHistorical_event();
}
//显示当前游戏角色的状态
public void display() {
System.out.println("玩家当前完成的历史事件为:" + this.historical_event);
}
public String getHistorical_event() {
return historical_event;
}
public void setHistorical_event(String historical_event) {
this.historical_event = historical_event;
}
}
//存档集合,用来保存多个备忘录(存档)
public class Caretaker {
//对 GameRole 保存多次状态
private List<Memento> mementos;
public Caretaker() {
mementos = new ArrayList<>();
}
public List<Memento> getMementos() {
return mementos;
}
public void addMementos(Memento memento) {
mementos.add(memento);
System.out.println("存档完成");
}
public void showMementos() {
for (Memento memento : mementos) {
System.out.println(mementos.indexOf(memento)+":"+memento.getHistorical_event());
}
}
}
//总结:GameRole 创建 Memento 对象,Caretaker 存入多个 GameRole ;Caretaker 调用 GameRole ,GameRole 再调用 Memento
//来显示存档
public class Client {
public static void main(String[] args) {
//创建游戏角色,完成官渡之战
GameRole gameRole = new GameRole();
gameRole.setHistorical_event("官渡之战");
gameRole.display();
//把当前状态保存 caretaker
Caretaker caretaker = new Caretaker();
caretaker.addMementos(gameRole.createMemento());
//游戏角色完成赤壁之战
gameRole.setHistorical_event("赤壁之战");
gameRole.display();
//把当前状态保存 caretaker
caretaker.addMementos(gameRole.createMemento());
//游戏角色完成三足鼎立
gameRole.setHistorical_event("三足鼎立");
gameRole.display();
//把当前状态保存 caretaker
caretaker.addMementos(gameRole.createMemento());
System.out.println("--------------");
System.out.println("查看所有存档:");
caretaker.showMementos();
System.out.println("--------------");
Scanner sc = new Scanner(System.in);
System.out.println("请输入要恢复的存档索引:");
int index = sc.nextInt();
gameRole.recoverGameRoleFromMemento(caretaker.getMementos().get(index));
System.out.println("恢复后的状态");
gameRole.display();
}
}
输出:
玩家当前完成的历史事件为:官渡之战
存档完成
玩家当前完成的历史事件为:赤壁之战
存档完成
玩家当前完成的历史事件为:三足鼎立
存档完成
--------------
查看所有存档:
0:官渡之战
1:赤壁之战
2:三足鼎立
--------------
请输入要恢复的存档索引:
1
恢复后的状态
玩家当前完成的历史事件为:赤壁之战
返回顶部
基本介绍
观察者模式:对象之间多对一依赖的一种设计方案,被依赖的对象为 Subject,依赖的对象为 Observer,Subject
通知 Observer 变化,比如这里的奶站是 Subject,是 1 的一方。用户时 Observer,是多的一方。
uml:
Subject:登记注册、移除和通知
addObserver 注 册
deleteObserver 移 除
notifyObservers() 通知所有的注册的用户,根据不同需求,可以是更新数据,让用户来取,也可能是实施推送, 看具体需求定
Observer:接收输入
//观察者必须最先创建,它定义了接收消息的方式
public interface Observer{
public void receiveMessage(String message);
}
//再创建主题,它定义了操作观察者的方法
public interface Subject{
public void addObserver(observer.Observer o);
public void deleteObserver(observer.Observer o);
public void notifyObservers();
}
//英雄继承观察者,实现具体接收消息的方法,创建时要将该英雄放入主题中,以便所有英雄统一接收消息
public class HuaMuLan implements Observer {
Subject subject;
//将对象添加到subject的集合中
public HuaMuLan(Subject subject) {
this.subject = subject;
subject.addObserver(this);
}
@Override
public void receiveMessage(String message) {
System.out.println("花木兰收到'"+message+"',正在前往支援");
}
}
public class XiangYu implements Observer {
Subject subject;
//将对象添加到subject的集合中
public XiangYu(Subject subject) {
this.subject = subject;
subject.addObserver(this);
}
@Override
public void receiveMessage(String message) {
System.out.println("项羽收到'"+message+"',正在前往支援");
}
}
//省略剩余两英雄
public class LanLinWang implements Subject {
private String message="";
private List<Observer> observers;
public LanLinWang() {
observers = new ArrayList<>();
}
@Override
public void addObserver(Observer o) {
if (!observers.contains(o)) {
observers.add(o);
}
}
@Override
public void deleteObserver(Observer o) {
if (observers.contains(o)) {
observers.remove(o);
}
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.receiveMessage(message);
}
}
public void publishMessage(String message){
this.message = message;
}
}
//总结:兰陵王要先将队友都添加到观察者集合中,再发送消息,这样队友同一时间都能接收同一消息,再调用各自的方法
public class Client {
public static void main(String[] args) {
LanLinWang lanLinWang = new LanLinWang();
new HuaMuLan(lanLinWang);
new YuJi(lanLinWang);
new ZhenJi(lanLinWang);
new XiangYu(lanLinWang);
String message = "兰陵王请求集合";
System.out.println(message);
lanLinWang.publishMessage(message);
lanLinWang.notifyObservers();
}
}
输出:
兰陵王请求集合
花木兰收到'兰陵王请求集合',正在前往支援
虞姬收到'兰陵王请求集合',正在前往支援
甄姬收到'兰陵王请求集合',正在前往支援
项羽收到'兰陵王请求集合',正在前往支援
返回顶部
public abstract class Customer {
public abstract void buy(Shop s);
}
public class CustomerOne extends Customer {
private Integer milktea;
private Integer cake;
public CustomerOne(Integer milktea, Integer cake) {
this.milktea = milktea;
this.cake = cake;
}
public Integer getMilktea() {
return milktea;
}
public Integer getCake() {
return cake;
}
@Override
public void buy(Shop s) {
s.payOne(this);
}
}
//顾客二省略
public interface Shop {
void payOne(CustomerOne one);
void payTwo(CustomerTwo two);
}
public class SalesMan implements Shop {
@Override
public void payOne(CustomerOne one) {
Integer milktea = one.getMilktea();
Integer cake = one.getCake();
System.out.println("顾客一");
caculate(milktea,cake);
}
@Override
public void payTwo(CustomerTwo two) {
Integer milktea = two.getMilktea();
Integer cake = two.getCake();
System.out.println("顾客二");
caculate(milktea,cake);
}
private void caculate(Integer milktea,Integer cake){
if((milktea + cake) >= 20)
System.out.println("打九折:"+(milktea + cake)*0.9);
else
System.out.println("不打折:"+(milktea + cake));
}
}
public class Client {
public static void main(String[] args) {
Shop salesMan=new SalesMan();
salesMan.payOne(new CustomerOne(12,5));
System.out.println("------------");
salesMan.payOne(new CustomerOne(15,8));
}
}
输出:
顾客一
不打折:17
------------
顾客一
打九折:20.7
返回顶部