设计模式

1. 简单工厂模式

简单工厂模式：静态工厂模式

static: 是类的成员变量，成员方法。不需要创建对象，通过类名调用；被类的所有对象共同拥有

抛出异常 Exception// 自定义异常，成绩管理 1-100,1-100 之外的就要捕获异常

java 中 throws 放在方法声明的地方，表示这个方法可能抛出异常

throw：在代码中抛出异常

如果属性没有 protected 或者 private，默认访问权限就是 package，同一个包访问。

private<package<protected<public. protected 用于继承，在父类用。

默认权限和 protected 的区别是包之间。

子类可以访问父类的 protected（非包子类）

​ 接口的方法默认 public abstract void fly ()

1.1 反面代码

Copy
package simpleFactory.negative;

abstract class Weapon{
abstract void display();
}

class MachineGun extends Weapon{

@Override
void display() {
// TODO Auto-generated method stub
System.out.println("机关枪");
}

}
class Pistol extends Weapon{

@Override
void display() {
// TODO Auto-generated method stub
System.out.println("手枪");
}

}
public class DemoN {
public static void main(String[] args) {
Weapon w1=new MachineGun();
w1.display();
Weapon w2=new Pistol();
w2.display();
}
/**
* 客户端需要只带具体子类名称，增加用户编程的难度
*/
}

1.2 正面代码

Copy
package simpleFactory.negative;

abstract class Weapon{
abstract void display();
}

class MachineGun extends Weapon{

@Override
void display() {
// TODO Auto-generated method stub
System.out.println("机关枪");
}

}
class Pistol extends Weapon{

@Override
void display() {
// TODO Auto-generated method stub
System.out.println("手枪");
}

}
public class DemoN {
public static void main(String[] args) {
Weapon w1=new MachineGun();
w1.display();
Weapon w2=new Pistol();
w2.display();
}
/**
* 客户端需要只带具体子类名称，增加用户编程的难度
*/
}

2. 工厂方法模式

2.1 反面代码

Copy
package factory.negative;

abstract class Weapon{
abstract void diaplay();
}

class MachineGun extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("机关枪");
}

}
class Pistol extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("手枪");
}

}
class SniperRifle extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("狙击步枪！");
}

}
class WeaponFactory{
public static Weapon creatWeapon(String type) {
Weapon w=null;
switch(type) {
case "手枪":
w=new Pistol();
break;
case "机关枪":
w=new MachineGun();
break;
case "狙击步枪":
w= new SniperRifle();
break;
default:
System.out.println("不能生产改武器："+type);

}
return w;
}
}
public class DemoN {
public static void main(String[] args) {
Weapon pistol=WeaponFactory.creatWeapon("手枪");
pistol.diaplay();
Weapon machineGun=WeaponFactory.creatWeapon("机关枪");
machineGun.diaplay();
Weapon sr=new SniperRifle();
sr.diaplay();
}
}

2.2 正面代码

Copy
package factory.positive;

abstract class Weapon{
abstract void diaplay();
}

class MachineGun extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("机关枪");
}

}
class Pistol extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("手枪");
}

}
class SniperRifle extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("狙击步枪！");
}

}
interface WeaponFactory{
Weapon createWeapon();
}
class MachineGunFactory implements WeaponFactory{

@Override
public Weapon createWeapon() {
// TODO Auto-generated method stub
return new MachineGun();
}

}
class SniperRifleFactory implements WeaponFactory{

@Override
public Weapon createWeapon() {
// TODO Auto-generated method stub
return new SniperRifle();
}

}
class PistolFactory implements WeaponFactory{

@Override
public Weapon createWeapon() {
// TODO Auto-generated method stub
return new Pistol();
}

}
public class DemoP {
public static void main(String[] args) {
WeaponFactory wf1=new MachineGunFactory();
Weapon w1=wf1.createWeapon();
w1.diaplay();
WeaponFactory wf2=new PistolFactory();
Weapon w2=wf2.createWeapon();
w2.diaplay();
WeaponFactory wf3=new SniperRifleFactory();
Weapon w3=wf3.createWeapon();
w3.diaplay();
}

}

3. 抽象工厂模式

3.1 反面

Copy
package abstractFactory.negative;

abstract class Weapon{
abstract void diaplay();
}

/**
* 使用工厂方法模式不使用抽象工厂模式，现如今现代化工厂要增加生产线——子弹类Bullet
*
* @author ASUS
*
*/
abstract class Bullet{
abstract void display();
}

/**
* 子弹类
* @author ASUS
*
*/
class PistolBullet extends Bullet{

@Override
void display() {
// TODO Auto-generated method stub
System.out.println("手枪子弹");
}

}
class MachineGunBullet extends Bullet{

@Override
void display() {
// TODO Auto-generated method stub
System.out.println("机关枪子弹");
}

}
//子弹工厂
interface BulletFactory{
Bullet creatBullet();
}

class MachineGun extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("机关枪");
}

}
class Pistol extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("手枪");
}

}
class SniperRifle extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("狙击步枪！");
}

}
interface WeaponFactory{
Weapon createWeapon();
}
class MachineGunFactory implements WeaponFactory{

@Override
public Weapon createWeapon() {
// TODO Auto-generated method stub
return new MachineGun();
}

}
class MachineGunBulletFactory implements BulletFactory{

@Override
public Bullet creatBullet() {
// TODO Auto-generated method stub
return new MachineGunBullet();
}

}
class SniperRifleFactory implements WeaponFactory{

@Override
public Weapon createWeapon() {
// TODO Auto-generated method stub
return new SniperRifle();
}

}
class PistolFactory implements WeaponFactory{

@Override
public Weapon createWeapon() {
// TODO Auto-generated method stub
return new Pistol();
}

}
//手枪子弹工厂
class PistolBulletFactory implements BulletFactory{

@Override
public Bullet creatBullet() {
// TODO Auto-generated method stub
return new PistolBullet();
}

}
public class DemoN {
public static void main(String[] args) {
WeaponFactory wf1=new MachineGunFactory();
Weapon w1=wf1.createWeapon();
w1.diaplay();
WeaponFactory wf2=new PistolFactory();
Weapon w2=wf2.createWeapon();
w2.diaplay();
WeaponFactory wf3=new SniperRifleFactory();
Weapon w3=wf3.createWeapon();
w3.diaplay();
BulletFactory bf1=new MachineGunBulletFactory();
Bullet b1=bf1.creatBullet();
b1.display();
}

}

3.2 正面

Copy
package abstractFactory.positive;

abstract class Weapon{
abstract void diaplay();
}

/**
* 使用工厂方法模式不使用抽象工厂模式，现如今现代化工厂要增加生产线——子弹类Bullet
*
* @author ASUS
*
*/
abstract class Bullet{
abstract void display();
}

/**
* 子弹类
* @author ASUS
*
*/
class PistolBullet extends Bullet{

@Override
void display() {
// TODO Auto-generated method stub
System.out.println("手枪子弹");
}

}
class MachineGunBullet extends Bullet{

@Override
void display() {
// TODO Auto-generated method stub
System.out.println("机关枪子弹");
}

}
//抽象工厂
interface ArsenalFactory{
Bullet creatBullet();
Weapon creatWeapon();
}

class MachineGun extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("机关枪");
}

}
class MachineGunFactory implements ArsenalFactory{

@Override
public Bullet creatBullet() {
// TODO Auto-generated method stub
return new MachineGunBullet();
}

@Override
public Weapon creatWeapon() {
// TODO Auto-generated method stub
return new MachineGun();
}

}
class PistolFactory implements ArsenalFactory{

@Override
public Bullet creatBullet() {
// TODO Auto-generated method stub
return new PistolBullet();
}

@Override
public Weapon creatWeapon() {
// TODO Auto-generated method stub
return new Pistol();
}

}
class Pistol extends Weapon{

@Override
void diaplay() {
// TODO Auto-generated method stub
System.out.println("手枪");
}

}
public class DemoP {
public static void main(String[] args) {
ArsenalFactory af1=new MachineGunFactory();
Weapon w1=af1.creatWeapon();
Bullet b1=af1.creatBullet();
w1.diaplay();
b1.display();

}

}

4. 建造者模式

4.1 反面

Copy
package builder.negative;

class LoggerQiang{
private String eye;
private String ear;
private String mouth;
public String getEye() {
return eye;
}
public void setEye(String eye) {
this.eye = eye;
}
public String getEar() {
return ear;
}
public void setEar(String ear) {
this.ear = ear;
}
public String getMouth() {
return mouth;
}
public void setMouth(String mouth) {
this.mouth = mouth;
}
@Override
public String toString() {
return "LoggerQiang [眼睛=" + eye + ", 耳朵=" + ear + ", 嘴巴=" + mouth + "]";
}

}
public class DemoN_A {
public static void main(String[] args) {
System.out.println("——————高兴的光头强————");
LoggerQiang qiang=new LoggerQiang();
qiang.setEar("耳朵竖起");
qiang.setEye("眼睛睁圆");
qiang.setMouth("嘴角上翘");
System.out.println(qiang);
}
/**
* 客户端直接组装光头强。
*/
}

Copy
package builder.negative;

class LoggerQiang{
private String eye;
private String ear;
private String mouth;
public String getEye() {
return eye;
}
public void setEye(String eye) {
this.eye = eye;
}
public String getEar() {
return ear;
}
public void setEar(String ear) {
this.ear = ear;
}
public String getMouth() {
return mouth;
}
public void setMouth(String mouth) {
this.mouth = mouth;
}
@Override
public String toString() {
return "LoggerQiang [眼睛=" + eye + ", 耳朵=" + ear + ", 嘴巴=" + mouth + "]";
}

}
//高兴的光头强
class HappyQiang{
private LoggerQiang qiang=new LoggerQiang();
public LoggerQiang build(){
this.qiang.setEar("耳朵竖起");
this.qiang.setEye("眼睛睁圆");
this.qiang.setMouth("嘴角上翘");
return this.qiang;
}
}
class DisappintedQiang{
private LoggerQiang qiang=new LoggerQiang();
public LoggerQiang build(){
this.qiang.setEar("耳朵收小");
this.qiang.setEye("眼皮下垂");
this.qiang.setMouth("嘴角下弯");
return this.qiang;
}
}
public class DemoN_B {
public static void main(String[] args) {
System.out.println("高兴的光头强");
HappyQiang qiang=new HappyQiang();
LoggerQiang hq=qiang.build();
System.out.println(hq);

System.out.println("沮丧的光头强");
DisappintedQiang qiang2=new DisappintedQiang();
LoggerQiang dq=qiang2.build();
System.out.println(dq);
}
}

4.2 正面代码

Copy
package builder.positive;

class LoggerQiang{
private String eye;
private String ear;
private String mouth;
public String getEye() {
return eye;
}
public void setEye(String eye) {
this.eye = eye;
}
public String getEar() {
return ear;
}
public void setEar(String ear) {
this.ear = ear;
}
public String getMouth() {
return mouth;
}
public void setMouth(String mouth) {
this.mouth = mouth;
}
@Override
public String toString() {
return "LoggerQiang [眼睛=" + eye + ", 耳朵=" + ear + ", 嘴巴=" + mouth + "]";
}

}
interface Builder{
void setEye();
void setEar();
void setMouth();
LoggerQiang getResult();
}

class HappyQiangBuilder implements Builder{
private LoggerQiang lq=new LoggerQiang();
@Override
public void setEye() {
// TODO Auto-generated method stub
this.lq.setEye("眼睛睁圆");
}

@Override
public void setEar() {
// TODO Auto-generated method stub
this.lq.setEar("耳朵竖起");
}

@Override
public void setMouth() {
// TODO Auto-generated method stub
this.lq.setMouth("嘴角上翘");

}

@Override
public LoggerQiang getResult() {
// TODO Auto-generated method stub
return this.lq;
}
}
class DisappintedQiangBuilder implements Builder{
private LoggerQiang lq=new LoggerQiang();

@Override
public void setEye() {
// TODO Auto-generated method stub
this.lq.setEye("眼皮下垂");
}

@Override
public void setEar() {
// TODO Auto-generated method stub
this.lq.setEar("耳朵收小");
}

@Override
public void setMouth() {
// TODO Auto-generated method stub
this.lq.setMouth("嘴角下弯");
}

@Override
public LoggerQiang getResult() {
// TODO Auto-generated method stub
return this.lq;
}

}
class Director{
private Builder builder;

public Director(Builder bulider) {
super();
this.builder = bulider;
}
public LoggerQiang build() {
this.builder.setEar();
this.builder.setEye();
this.builder.setMouth();
return this.builder.getResult();
}
}
public class DemoP {
public static void main(String[] args) {
System.out.println("高兴的光头强");
Builder hqb=new HappyQiangBuilder();
LoggerQiang lq1=new Director(hqb).build();
System.out.println(lq1);
System.out.println("沮丧的光头强");
Builder dbq=new DisappintedQiangBuilder();
LoggerQiang lq2=new Director(dbq).build();
System.out.println(lq2);
}

}

5. 原型模式

5.1 反面代码

Copy
package prototype.negative;
class Weather{
private String city;
private String date;
private String weatherPhenmenon;
private String airQuality;
private String wind;
public Weather(String city, String date, String weatherPhenmenon, String airQuality, String wind) {
super();
this.city = city;
this.date = date;
this.weatherPhenmenon = weatherPhenmenon;
this.airQuality = airQuality;
this.wind = wind;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getWeatherPhenmenon() {
return weatherPhenmenon;
}
public void setWeatherPhenmenon(String weatherPhenmenon) {
this.weatherPhenmenon = weatherPhenmenon;
}
public String getAirQuality() {
return airQuality;
}
public void setAirQulity(String airQuality) {
this.airQuality = airQuality;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
@Override
public String toString() {
return "Weather [城市=" + city + ", 日期=" + date + ", 天气现象=" + weatherPhenmenon + ", 空气质量="
+ airQuality + ", 风=" + wind + "]";
}

}
public class DemoN {
public static void main(String[] args) {
Weather today=new Weather("张家界","2021年10月24日","小雨","优","东北风 微风");
System.out.println(today);
System.out.println("第二天只有日期和天气现象改变，没有其他要素要改变");
Weather tomorrow=new Weather("张家界","2021年10月25日","多云","优","东北风 微风");
System.out.println(tomorrow);
}
}

5.2.1 正面代码 ——A

Copy
package prototype.positive.a;
class WeatherDate{
private String year;
private String month;
private String day;
public WeatherDate(String year, String month, String day) {
super();
this.year = year;
this.month = month;
this.day = day;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
@Override
public String toString() {
return "WeatherDate [年=" + year + ", 月=" + month + ", 日=" + day + "]";
}

}
class Weather implements Cloneable{
private String city;
private WeatherDate date;
private String weatherPhenmenon;
private String airQuality;
private String wind;
public Weather(String city, WeatherDate date, String weatherPhenmenon, String airQuality, String wind) {
super();
this.city = city;
this.date = date;
this.weatherPhenmenon = weatherPhenmenon;
this.airQuality = airQuality;
this.wind = wind;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public WeatherDate getDate() {
return date;
}
public void setDate(WeatherDate date) {
this.date = date;
}
public String getWeatherPhenmenon() {
return weatherPhenmenon;
}
public void setWeatherPhenmenon(String weatherPhenmenon) {
this.weatherPhenmenon = weatherPhenmenon;
}
public String getAirQuality() {
return airQuality;
}
public void setAirQulity(String airQuality) {
this.airQuality = airQuality;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
@Override
public String toString() {
return "Weather [城市=" + city + ", 日期=" + date + ", 天气现象=" + weatherPhenmenon + ", 空气质量="
+ airQuality + ", 风=" + wind + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Object obj=null;
obj=super.clone();
return obj;
}

}
public class DemoP {
public static void main(String[] args) throws CloneNotSupportedException {
Weather today=new Weather("张家界",new WeatherDate("2021","10","24"),"小雨","优","东北风 微风");
System.out.println(today);
System.out.println("第二天只有日期和天气现象改变，没有其他要素要改变");
Weather tomorrow=(Weather)today.clone();
tomorrow.getDate().setDay("25");
tomorrow.setWeatherPhenmenon("多云");
System.out.println(tomorrow);
System.out.println("再输出today\n"+today);//浅克隆今天和以前的今天不一样

}
}

5.2.2 正面代码 ——B

Copy
package prototype.positive.b;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
interface WeatherPrototype{
Object cloneMe() throws Exception;

}
class Weather implements WeatherPrototype,Serializable{
private String city;
private String date;
private String weatherPhenmenon;
private String airQuality;
private String wind;
public Weather(String city, String date, String weatherPhenmenon, String airQuality, String wind) {
super();
this.city = city;
this.date = date;
this.weatherPhenmenon = weatherPhenmenon;
this.airQuality = airQuality;
this.wind = wind;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getWeatherPhenmenon() {
return weatherPhenmenon;
}
public void setWeatherPhenmenon(String weatherPhenmenon) {
this.weatherPhenmenon = weatherPhenmenon;
}
public String getAirQuality() {
return airQuality;
}
public void setAirQulity(String airQuality) {
this.airQuality = airQuality;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
@Override
public String toString() {
return "Weather [城市=" + city + ", 日期=" + date + ", 天气现象=" + weatherPhenmenon + ", 空气质量="
+ airQuality + ", 风=" + wind + "]";
}
@Override
public Object cloneMe() throws Exception {
// TODO Auto-generated method stub
Object obj=null;
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis =new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois=new ObjectInputStream(bis);
obj=ois.readObject();
return obj;
}

}
public class DemoP {
public static void main(String[] args) throws Exception {
Weather today=new Weather("张家界","2021年10月24日","小雨","优","东北风 微风");
System.out.println(today);
System.out.println("第二天只有日期和天气现象改变，没有其他要素要改变");
Weather tomrrow=(Weather)today.cloneMe();
tomrrow.setDate("2021年10月25日");
tomrrow.setWeatherPhenmenon("多云");
System.out.println(tomrrow);
}
}

5.2.3 正面代码 ——C

Copy
package prototype.positive.c;
class WeatherDate implements Cloneable {
private String year;
private String month;
private String day;
public WeatherDate(String year, String month, String day) {
super();
this.year = year;
this.month = month;
this.day = day;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
@Override
public String toString() {
return "WeatherDate [年=" + year + ", 月=" + month + ", 日=" + day + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}

}
class Weather implements Cloneable{
private String city;
private WeatherDate date;
private String weatherPhenmenon;
private String airQuality;
private String wind;
public Weather(String city, WeatherDate date, String weatherPhenmenon, String airQuality, String wind) {
super();
this.city = city;
this.date = date;
this.weatherPhenmenon = weatherPhenmenon;
this.airQuality = airQuality;
this.wind = wind;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public WeatherDate getDate() {
return date;
}
public void setDate(WeatherDate date) {
this.date = date;
}
public String getWeatherPhenmenon() {
return weatherPhenmenon;
}
public void setWeatherPhenmenon(String weatherPhenmenon) {
this.weatherPhenmenon = weatherPhenmenon;
}
public String getAirQuality() {
return airQuality;
}
public void setAirQulity(String airQuality) {
this.airQuality = airQuality;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
@Override
public String toString() {
return "Weather [城市=" + city + ", 日期=" + date + ", 天气现象=" + weatherPhenmenon + ", 空气质量="
+ airQuality + ", 风=" + wind + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Object obj=null;
obj=super.clone();
this.date=(WeatherDate)this.date.clone();
return obj;
}
}
public class DemoP {//深克隆
public static void main(String[] args) throws CloneNotSupportedException {
Weather today=new Weather("张家界",new WeatherDate("2021","10","24"),"小雨","优","东北风 微风");
System.out.println(today);
System.out.println("第二天只有日期和天气现象改变，没有其他要素要改变");
Weather tomorrow=(Weather)today.clone();
tomorrow.getDate().setDay("25");
tomorrow.setWeatherPhenmenon("多云");
System.out.println(tomorrow);
System.out.println("再输出today\n"+today);
}
}

6. 单例模式

6.1 反面代码

Copy
package singleton.negative;

class Moon{
private double radius=1738.14;
private String state;//形状
public Moon(String state) {
super();
this.state = state;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return "Moon [半径=" + radius + ", 形状=" + state + "]";
}

}
class Bear{
private String name;

public Bear(String name) {
super();
this.name = name;
}
public void look(Moon moon) {
System.out.println(this.name+"看见的月亮石："+moon);
}
}
public class DemoN {
public static void main(String[] args) {
Moon m1=new Moon("满月");
Moon m2=new Moon("半月");
Bear big=new Bear("熊大");
Bear little=new Bear("熊二");
big.look(m1);
little.look(m2);
//天空只能有一个月亮，违背事实

}
}

6.2 正面代码

Copy
package singleton.positive.A;

/**
* 饿汉式单例模式
* （1）不需要考虑多个线程同时访问的问题
* （2）调用速度和反应时间优于懒汉式单例模式
* （3）资源利用率不及懒汉式单例系统加载时间比较长
* @author ASUS
*
*/
class Moon{
private final double radius=1738.14;
private String state;//形状
//（1）静态私有成员
private static final Moon instance=new Moon();
//私有化构造方法，外部不能new新对象
private Moon() {

}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
//公有的工厂方法，或者唯一对象
public static Moon getInstance() {
return instance;
}
@Override
public String toString() {
return "Moon [半径=" + radius + ", 形状=" + state + "]";
}

}
class Bear{
private String name;

public Bear(String name) {
super();
this.name = name;
}
public void look(Moon moon) {
System.out.println(this.name+"看见的月亮是："+moon);
}
}
public class DemoP_1 {
public static void main(String[] args) {
// Moon m1=new Moon("");不能new对象，因为构造方法私有化
Moon m1=Moon.getInstance();
Moon m2=Moon.getInstance();
m1.setState("满月");
m2.setState("半月");
Bear big=new Bear("熊大");
Bear little=new Bear("熊二");
big.look(m1);
little.look(m2);
System.out.println(m1.hashCode());
System.out.println(m2.hashCode());
}
}

Copy
package singleton.positive.B;
/**
* 懒汉式单例模式
* （1）实现了延时加载//需要时加载
* （2）必须处理多个线程同时访问资源
* （3）需通过双重检查锁定等机制进行控制，将导致系统性能受到一定影响
* @author ASUS
*
*/
class Moon{
private final double radius=1738.14;
private String state;//形状
//（1）静态私有成员
private static Moon instance=null;//不是常量，不用final

//私有化构造方法，外部不能new新对象
private Moon() {

}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
//公有的工厂方法，或者唯一对象
public static synchronized Moon getInstance() {
if(instance==null)
instance=new Moon();
return instance;
}
@Override
public String toString() {
return "Moon [半径=" + radius + ", 形状=" + state + "]";
}

}
class Bear{
private String name;

public Bear(String name) {
super();
this.name = name;
}
public void look(Moon moon) {
System.out.println(this.name+"看见的月亮是："+moon);
}
}
public class DemoP_2 {
public static void main(String[] args) {
// Moon m1=new Moon("");不能new对象，因为构造方法私有化
Moon m1=Moon.getInstance();
Moon m2=Moon.getInstance();
m1.setState("满月");
m2.setState("半月");
Bear big=new Bear("熊大");
Bear little=new Bear("熊二");
big.look(m1);
little.look(m2);
System.out.println(m1.hashCode());
System.out.println(m2.hashCode());
}
}

Copy
package singleton.positive.C;
/**
* 静态内部类单例模式
* （1）线程安全，没有延迟加载，效率和饿汉式一样，具有懒汉式和饿汉式的优点
*
* @author ASUS
*
*/
class Moon{
private final double radius=1738.14;
private String state;//形状
//（1）静态内部类
private static class MoonInstance{
private static Moon instance=new Moon();
}

//私有化构造方法，外部不能new新对象
private Moon() {

}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
//公有的工厂方法，或者唯一对象
public static Moon getInstance() {
return MoonInstance.instance;
}
@Override
public String toString() {
return "Moon [半径=" + radius + ", 形状=" + state + "]";
}

}
class Bear{
private String name;

public Bear(String name) {
super();
this.name = name;
}
public void look(Moon moon) {
System.out.println(this.name+"看见的月亮是："+moon);
}
}
public class DemoP_3 {
public static void main(String[] args) {
// Moon m1=new Moon("");不能new对象，因为构造方法私有化
Moon m1=Moon.getInstance();
Moon m2=Moon.getInstance();
m1.setState("满月");
// m2.setState("半月");
Bear big=new Bear("熊大");
Bear little=new Bear("熊二");
big.look(m1);
little.look(m2);
System.out.println(m1.hashCode());
System.out.println(m2.hashCode());
}
}

7. 模板方法模式

7.1 反面代码

Copy
package templateMethod.negative;
class LoggerQiang{
public void workOn() {//剧情1
System.out.println("光头强准备砍树！");
System.out.println("光头强出发了");
System.out.println("光头强用电锯砍树！");
System.out.println("光头强开车运输木材");
System.out.println("光头强不需要贩卖木材！");
System.out.println("光头强吃午饭");
}

}
class LoggerQiang2{
public void workOn() {//剧情1
System.out.println("光头强准备砍树！");
System.out.println("光头强出发了");
System.out.println("光头强用斧头砍树！");
System.out.println("光头强用三轮车运输木材");
System.out.println("光头强贩卖木材！");
System.out.println("光头强吃午饭");
}

}
public class DemoN {
public static void main(String[] args) {
new LoggerQiang().workOn();

System.out.println("剧情2");
new LoggerQiang2().workOn();
}
/**
* 缺点
* （1）伐木过程系统，但是采用不同的具体方式
* （2）违反了开闭原则
* （3）违反了依赖倒置原则
*/
}

7.2 正面代码

Copy
package templateMethod.positive;
abstract class LoggerTemplate{
protected void ready() {
System.out.println("光头强在准备...");

}
protected void setout() {
System.out.println("光头强出发了...");
}
protected void sellToother() {
System.out.println("光头强自己卖木头...");
}
protected void sellToli() {
System.out.println("光头强把木头卖给李老板...");
}
protected boolean isSell() {
return true;

}
public void eat() {
System.out.println("光头强吃午饭...");
}
protected abstract void cutTree();
protected abstract void transport();
//模板方法
public final void workOn(){
this.ready();
this.setout();
this.cutTree();
this.transport();
if(isSell())//如果为真，光头强自卖木头
this.sellToother();
else
this.sellToli();
this.eat();
}
}
class LoggerQiang extends LoggerTemplate{

@Override
protected void cutTree() {
// TODO Auto-generated method stub
System.out.println("用电锯砍树");
}

@Override
protected void transport() {
// TODO Auto-generated method stub
System.out.println("用卡车运输木头");
}

}
class LoggerQiang1 extends LoggerTemplate{

@Override
protected void cutTree() {
// TODO Auto-generated method stub
System.out.println("用斧头砍树...");
}

@Override
protected void transport() {
// TODO Auto-generated method stub
System.out.println("用三轮车运输木材...");
}
public boolean isSell() {
return false;
}
}
public class DemoP {
public static void main(String[] args) {
System.out.println("剧情1————————");
LoggerTemplate a=new LoggerQiang();
a.workOn();
System.out.println("剧情2————————");
LoggerTemplate b=new LoggerQiang1();
b.workOn();
}//符合开闭原则

}

8. 中介者模式

8.1 反面代码

Copy
package mediator.negative;
class BankAccount{
private double money;

public BankAccount(double money) {
super();
this.money = money;
}

public double getMoney() {
return money;
}

public void setMoney(double money) {
this.money = money;
}
public void deposit(double money) {
this.money+=money;

}
public void withDraw(double money) {
this.money-=money;
}
}
class Sale{
private int number=5;
private double prive=111;
private BankAccount bank=new BankAccount(100);
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public double getPrive() {
return prive;
}
public void setPrive(double prive) {
this.prive = prive;
}
public BankAccount getBank() {
return bank;
}
public void setBank(BankAccount bank) {
this.bank = bank;
}
public void sellHouse(int saleNumber) {//卖房子
Purchase purchase=new Purchase();//买房子的
purchase.buyHouse(saleNumber);
double money=saleNumber*prive;//销售款
this.bank.deposit(money);//销售者存款
this.number=this.number-saleNumber;//房子数量减少

}
@Override
public String toString() {
return "Sale [数量=" + number + ", 单价=" + prive + ", 账户=" + bank.getMoney() + "]";
}

}
class Purchase{
private int number;
private BankAccount bank=new BankAccount(2000);
public void buyHouse(int buyNumber) {
this.number+=buyNumber;
Sale sale=new Sale();
sale.setNumber(sale.getNumber()-buyNumber);
double money=sale.getPrive()*buyNumber;
this.bank.withDraw(money);
}
@Override
public String toString() {
return "Purchase [数量" + number + ", 账户" + bank.getMoney() + "]";
}

}

public class DemoN {
public static void main(String[] args) {
Sale sale=new Sale();
Purchase pur=new Purchase();
System.out.println("___交易之前状态——————");
System.out.println("卖房者"+sale);
System.out.println("买房者"+pur);
sale.sellHouse(2);
pur.buyHouse(2);
System.out.println("交易之后状态");
System.out.println("卖房者"+sale);
System.out.println("买房者"+pur);
}

}

8.2 正面代码

Copy
package mediator.positive;

abstract class AbstractMediator{
protected Sale sale;
protected Purchase purchase;
public AbstractMediator() {
super();
this.sale = new Sale(this);
this.purchase = new Purchase(this);
}
public void register(AbstractColleague coll) {
String name=coll.getClass().getSimpleName();
if(name.equalsIgnoreCase("Sale"))
this.sale=(Sale)coll;
else if(name.equalsIgnoreCase("Purchase"))
this.purchase=(Purchase)coll;
}
abstract void sellHouse(int number);
abstract void buyHouse(int number);

}
class Mediator extends AbstractMediator{
public Mediator() {

}

@Override
void sellHouse(int number) {
// TODO Auto-generated method stub
this.sale.setNumber(this.sale.getNumber()-number);

double money=this.sale.getPrice()*number;
this.sale.getBank().deposit(money);
}

@Override
void buyHouse(int number) {
// TODO Auto-generated method stub
this.purchase.setNumber(this.purchase.getNumber()+number);

double money=this.sale.getPrice()*number;
this.purchase.getBank().withDraw(money);
}

}
abstract class AbstractColleague{
protected AbstractMediator mediator;

public AbstractColleague() {
super();
}

public AbstractColleague(AbstractMediator mediator) {
super();
this.mediator = mediator;
}

}
class Sale extends AbstractColleague{
private BankAccount bank;
private int number=5;
private double price=111;
public Sale() {

}
public Sale(AbstractMediator mediator) {
super(mediator);
this.bank=new BankAccount();
mediator.register(this);
}
public BankAccount getBank() {
return bank;
}
public void setBank(BankAccount bank) {
this.bank = bank;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public void sellHouse(int saleNumber) {
this.mediator.sellHouse(saleNumber);
}
@Override
public String toString() {
return "Sale [银行账户=" + bank.getMoney() + ", 数量=" + number + ", 单价=" + price + "]";
}

}
class Purchase extends AbstractColleague{
private int number;
private BankAccount bank;
public Purchase(AbstractMediator mediator) {
super(mediator);
this.bank=new BankAccount();
this.mediator.register(this);
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public BankAccount getBank() {
return bank;
}
public void setBank(BankAccount bank) {
this.bank = bank;
}
public void buyHouse(int number) {
this.mediator.buyHouse(number);
}
@Override
public String toString() {
return "Purchase [数量=" + number + ", 账户=" + bank.getMoney() + "]";
}

}
class BankAccount extends AbstractColleague{
private double money=0;

public double getMoney() {
return money;
}

public void setMoney(double money) {
this.money = money;
}
public void deposit(double money) {
this.money=this.money+money;
}
public void withDraw(double money) {
this.money=this.money-+money;
}

@Override
public String toString() {
return "BankAccount [money=" + money + "]";
}

}
public class Demo {

public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractMediator mediator=new Mediator();

Sale sale=new Sale(mediator);
Purchase pur=new Purchase(mediator);
pur.getBank().deposit(99999);
System.out.println("___交易之前状态——————");
System.out.println("卖房者"+sale);
System.out.println("买房者"+pur);
sale.sellHouse(2);
pur.buyHouse(2);
System.out.println("交易之后状态");
System.out.println("卖房者"+sale);
System.out.println("买房者"+pur);
}

}

9. 命令模式

9.1 反面代码：

Copy
package command.negaative;

class Cook{
public void beef(){
System.out.println("一盘牛肉");
}
public void duck(){
System.out.println("一盘酱板鸭");
}
public void chineseCabbage(){
System.out.println("一大白菜");
}
}
public class Demo {
//责任不清，缺少一个服务员角色
//需要采用命令模式
public static void main(String[] args) {
new Cook().beef();
new Cook().chineseCabbage();
}
}

9.2 正面代码：

Copy
package command.positive;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

class Cook{
public void beef(){
System.out.println("一盘牛肉");
}
public void duck(){
System.out.println("一盘酱板鸭");
}
public void chineseCabbage(){
System.out.println("一大白菜");
}
}
//抽象命令
abstract class Command{
protected Cook cook;

public Command(Cook cook) {
this.cook = cook;
}
abstract void execute();
}
class BeefCommand extends Command{
public BeefCommand(Cook cook) {
super(cook);
}

@Override
void execute() {
this.cook.beef();
}
}
class DuckCommand extends Command{
public DuckCommand(Cook cook) {
super(cook);
}

@Override
void execute() {
this.cook.duck();
}
}
class ChineseCabbage extends Command{
public ChineseCabbage(Cook cook) {
super(cook);
}

@Override
void execute() {
this.cook.chineseCabbage();
}
}
class Waiter{
private Command command;

public Command getCommand() {
return command;
}

public void setCommand(Command command) {
this.command = command;
}
public void orderDishes(){
this.command.execute();
}
}
class WaitList{
private List<Command> menu=new ArrayList<>();
public void adCommand(Command command){
this.menu.add(command);
}
public void orderDisher(){
for(Command command:menu){
command.execute();
}
}
}
public class Demo {
public static void main(String[] args) {
Cook wang=new Cook();
Command beef=new BeefCommand(wang);
Command duck=new DuckCommand(wang);
Command cabbage=new ChineseCabbage(wang);

Waiter xiaoer=new Waiter();

xiaoer.setCommand(beef);
xiaoer.orderDishes();
xiaoer.setCommand(duck);
xiaoer.orderDishes();
xiaoer.setCommand(cabbage);
xiaoer.orderDishes();

System.out.println("第二种情况：一起点（不是一个一个点餐）");
WaitList waitList = new WaitList();
waitList.adCommand(cabbage);
waitList.adCommand(duck);
waitList.adCommand(beef);
waitList.orderDisher();
}
}

10. 策略模式

10.1 反面代码：

10.2 正面代码：

装饰器模式

外观模式（实验 3 的题）

实验代码：

Copy
package facadePattern;

public abstract class AbstractFacade {
public abstract void execute();
}

Copy
package facadePattern;

class FileOperation{
public void read(){
System.out.println("文件操作");
}
}
class XMLDataConvertor{
public void convert(){
System.out.println("XML格式转换");
}
}
class DataAnalysis{
public void handle(){
System.out.println("数据分析");
}
}
class ReportDisplay{
public void display(){
System.out.println("结果展示");
}
}

Copy
package facadePattern;

public class FileFacade extends AbstractFacade{
private XMLDataConvertor xmlDataConvertor;
private DataAnalysis dataAnalysis;
private ReportDisplay reportDisplay;

public FileFacade() {
this.xmlDataConvertor = new XMLDataConvertor();
this.dataAnalysis = new DataAnalysis();
this.reportDisplay = new ReportDisplay();
}

@Override
public void execute() {
xmlDataConvertor.convert();
dataAnalysis.handle();
reportDisplay.display();
}
}

Copy
package facadePattern;

class FileOperation{
public void read(){
System.out.println("文件操作");
}
}
class XMLDataConvertor{
public void convert(){
System.out.println("XML格式转换");
}
}
class DataAnalysis{
public void handle(){
System.out.println("数据分析");
}
}
class ReportDisplay{
public void display(){
System.out.println("结果展示");
}
}

Copy
package facadePattern;

public class client {
public static void main(String[] args) {
FileFacade f=new FileFacade();//无需进行格式转换的类
f.execute();
System.out.println("-----");
XMLFacade x=new XMLFacade();//需要进行格式转换的类
x.execute();
}
}