外观模式
package test12; public class Memory { public void check(){ System.out.println("内存自检"); } } package test12; public class HardDisk { public void read(){ System.out.println("硬盘读取"); } } package test12; public class CPU { public void run(){ System.out.println("CPU运行"); } } package test12; public class OS { public void load(){ System.out.println("操作系统的载入"); } } package test12; public class Mainframe { private Memory memory; private CPU cpu; private HardDisk hardDisk; private OS os; public Mainframe() { memory=new Memory(); cpu=new CPU(); hardDisk=new HardDisk(); os=new OS(); } public void on(){ System.out.println("计算机开机。。。"); memory.check(); cpu.run(); hardDisk.read(); os.load(); System.out.println("计算机开机成功"); } }
package test12; public class Client { public static void main(String[] args) { Mainframe mainframe=new Mainframe(); mainframe.on(); } }
享元模式
package test13; // 享元接口 interface ChessPiece { void display(int x, int y); }
package test13; class WhiteChessPiece implements ChessPiece { @Override public void display(int x, int y) { System.out.println("在坐标(" + x + ", " + y + ")显示白棋"); } } package test13; class BlackChessPiece implements ChessPiece { @Override public void display(int x, int y) { System.out.println("在坐标(" + x + ", " + y + ")显示黑棋"); } }
package test13; class ChessFactory { private static ChessPiece whiteChessPiece; private static ChessPiece blackChessPiece; // 获取白棋对象 static ChessPiece getWhiteChessPiece() { if (whiteChessPiece == null) { whiteChessPiece = new WhiteChessPiece(); } return whiteChessPiece; } // 获取黑棋对象 static ChessPiece getBlackChessPiece() { if (blackChessPiece == null) { blackChessPiece = new BlackChessPiece(); } return blackChessPiece; } } package test13; public class Client { public static void main(String[] args) { // 获取享元工厂对象 ChessFactory chessFactory = new ChessFactory(); // 在不同位置显示白棋 ChessPiece whiteChess1 = chessFactory.getWhiteChessPiece(); whiteChess1.display(1, 1); ChessPiece whiteChess2 = chessFactory.getWhiteChessPiece(); whiteChess2.display(2, 2); // 在不同位置显示黑棋 ChessPiece blackChess1 = chessFactory.getBlackChessPiece(); blackChess1.display(3, 3); ChessPiece blackChess2 = chessFactory.getBlackChessPiece(); blackChess2.display(4, 4); } }
标签:12,ChessPiece,package,void,System,class,实验,设计模式,public From: https://www.cnblogs.com/syhxx/p/17832442.html