設計模式#
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 反面代碼#
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 正面代碼#
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 反面代碼#
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 正面代碼#
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 反面#
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 正面#
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 反面#
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);
}
/**
* 客戶端直接組裝光頭強。
*/
}
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 正面代碼#
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 反面代碼#
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#
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#
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#
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 反面代碼#
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 正面代碼#
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());
}
}
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());
}
}
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 反面代碼#
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 正面代碼#
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 反面代碼#
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 正面代碼#
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 反面代碼:#
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 正面代碼:#
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 的題)#
實驗代碼:
package facadePattern;
public abstract class AbstractFacade {
public abstract void execute();
}
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("結果展示");
}
}
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();
}
}
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("結果展示");
}
}
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();
}
}