装饰模式
定义抽象父类
public abstract class InputStream {
public abstract int read();
public abstract int read(byte[] buffer);
}
定义子类的原始输入流
import java.util.Arrays;
public class FileInputStream extends InputStream{
@Override
public int read() {
System.out.println("Read a single byte [a] originally.");
return 97;
}
@Override
public int read(byte[] buffer) {
buffer[0] = 97;
buffer[1] = 98;
buffer[2] = 99;
System.out.println("Read a byte array originally: "+ Arrays.toString(buffer));
return 3;
}
}
定义子类缓冲输入流
public class BufferedInputStream extends InputStream{
private InputStream is;
public BufferedInputStream(InputStream is) {
this.is = is;
}
@Override
public int read() {
System.out.println("offer a 8kb size buffer, enhance the reading performance.");
return is.read();
}
@Override
public int read(byte[] buffer) {
System.out.println("offer a 8kb size buffer, enhance the reading performance.");
return is.read(buffer);
}
}
装饰模式的测试执行类
public class DecoratorPatternDemo1 {
public static void main(String[] args) {
InputStream is = new BufferedInputStream(new FileInputStream());
System.out.println(is.read());
System.out.println(is.read(new byte[3]));
}
}
文章目录
工厂模式
抽象父类
public abstract class GameMachine {
private String name;
private double price;
public abstract void start();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
子类一
public class PS5 extends GameMachine{
@Override
public void start() {
System.out.println("["+getName()+"] start running Redemption1~~~");
}
}
子类二
public class XboxS extends GameMachine{
@Override
public void start() {
System.out.println("["+getName()+"] start running Redemption2~~~");
}
}
工厂类
public class Factory {
public static GameMachine createGamer(String info){
switch (info){
case "PS5":
GameMachine gm = new PS5();
gm.setName("PlayStation 5");
gm.setPrice(9999.9);
return gm;
case "xbox":
GameMachine gm1 = new XboxS();
gm1.setName("Xbox 1S");
gm1.setPrice(10000.0);
return gm1;
default:
return null;
}
}
}
执行体
public class FactoryDemo1 {
public static void main(String[] args) {
GameMachine gm1 = Factory.createGamer("xbox");
GameMachine gm2 = Factory.createGamer("PS5");
gm1.start();
gm2.start();
}
}



