java几种简单的设计模式

单例设计模式

//单例
public class Student {
    private Student(){}
    private static Student instance = new Student();
    public Student getInstance() {
        return instance;
    }
}

组合设计模式

//组合
public class Coder {
    private Computer com;
    public Coder(Computer com) {
        this.com = com;
    }
}

public class Computer {

}

模版方法设计模式

public class Test {

    /**
     *模板方法
     */
    public static void main(String[] args) {
        AbstractPrinter printer = new MyPrinter();
        printer.run();
    }

}

abstract class AbstractPrinter {
    public final void run() {
    
        open();
        close();
    }
    abstract void open();
    abstract void close();
}

class MyPrinter extends AbstractPrinter{

    @Override
    void close() {
        System.out.println("close");
    }

    @Override
    void open() {
        System.out.println("open");
    }
    
}

装饰设计模式

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Man man = new Man();
        SuperMan sm = new SuperMan(man);
        sm.eat();
    }

}

class Man {
    public void eat() {
        System.out.println("eating!!!!");
    }
    
    public void run() {
        System.out.println("running!!!!");
    }
}

class SuperMan {
    private Man man;
    public SuperMan(Man man) {
        this.man = man;
    }
    
    public void eat() {
        System.out.println("lai yi bei");
        man.eat();
        System.out.println("lai yi gen");
    }
    
    public void run() {
        man.run();
    }
    
    public void fly() {
        System.out.println("fly");
    }
}

 

 

 

好的,我来为您简单介绍几种常用的Java设计模式,并附上示例代码。 1. 工厂模式(Factory Pattern) 定义:工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式,而无需向客户端暴露创建逻辑,并且是通过使用一个公共接口来指向新创建的对象。 示例代码:假设我们有一个形状(Shape)接口,有三个不同的实现:圆形(Circle)、矩形(Rectangle)和正方形(Square)。我们可以使用工厂模式创建这些形状。 ``` public interface Shape { void draw(); } public class Circle implements Shape { @Override public void draw() { System.out.println("Drawing Circle"); } } public class Rectangle implements Shape { @Override public void draw() { System.out.println("Drawing Rectangle"); } } public class Square implements Shape { @Override public void draw() { System.out.println("Drawing Square"); } } public class ShapeFactory { public Shape getShape(String shapeType) { if (shapeType == null) { return null; } if (shapeType.equalsIgnoreCase("CIRCLE")) { return new Circle(); } else if (shapeType.equalsIgnoreCase("RECTANGLE")) { return new Rectangle(); } else if (shapeType.equalsIgnoreCase("SQUARE")) { return new Square(); } return null; } } ``` 我们可以使用ShapeFactory类来获取不同类型的形状对象: ``` ShapeFactory shapeFactory = new ShapeFactory(); Shape circle = shapeFactory.getShape("CIRCLE"); circle.draw(); Shape rectangle = shapeFactory.getShape("RECTANGLE"); rectangle.draw(); Shape square = shapeFactory.getShape("SQUARE"); square.draw(); ``` 2. 单例模式(Singleton Pattern) 定义:单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供一个全局访问点。 示例代码:假设我们有一个Settings类,用于存储应用程序的设置信息。我们可以使用单例模式确保只有一个Settings实例,以便在整个应用程序中共享设置。 ``` public class Settings { private static Settings instance = new Settings(); private Settings() {} public static Settings getInstance() { return instance; } public void setSetting(String key, String value) { // ... } public String getSetting(String key) { // ... return null; } } ``` 我们可以通过Settings.getInstance()方法获取Settings的唯一实例: ``` Settings settings = Settings.getInstance(); settings.setSetting("fontSize", "14"); String fontSize = settings.getSetting("fontSize"); ``` 3. 观察者模式(Observer Pattern) 定义:观察者模式是一种行为型设计模式,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,当主题对象发生变化时,它的所有观察者都会收到通知并更新自己的状态。 示例代码:假设我们有一个Subject接口和两个实现:WeatherData和StockData,它们都维护着一些数据。我们可以使用观察者模式来让多个观察者监听这些主题对象的变化。 ``` public interface Subject { void registerObserver(Observer o); void removeObserver(Observer o); void notifyObservers(); } public interface Observer { void update(float temperature, float humidity, float pressure); } public class WeatherData implements Subject { private List<Observer> observers = new ArrayList<>(); private float temperature; private float humidity; private float pressure; @Override public void registerObserver(Observer o) { observers.add(o); } @Override public void removeObserver(Observer o) { observers.remove(o); } @Override public void notifyObservers() { for (Observer o : observers) { o.update(temperature, humidity, pressure); } } public void setMeasurements(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; measurementsChanged(); } private void measurementsChanged() { notifyObservers(); } } public class StockData implements Subject { private List<Observer> observers = new ArrayList<>(); private String symbol; private float price; @Override public void registerObserver(Observer o) { observers.add(o); } @Override public void removeObserver(Observer o) { observers.remove(o); } @Override public void notifyObservers() { for (Observer o : observers) { o.update(price); } } public void setPrice(float price) { this.price = price; priceChanged(); } private void priceChanged() { notifyObservers(); } } public class CurrentConditionsDisplay implements Observer { private float temperature; private float humidity; @Override public void update(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; display(); } private void display() { System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity"); } } public class StockPriceDisplay implements Observer { private float price; @Override public void update(float price) { this.price = price; display(); } private void display() { System.out.println("Stock price: $" + price); } } ``` 我们可以创建一个WeatherData对象和一个StockData对象,并向它们注册两个观察者:CurrentConditionsDisplay和StockPriceDisplay。当WeatherData或StockData对象中的数据发生变化时,它们会通知它们的观察者。 ``` WeatherData weatherData = new WeatherData(); StockData stockData = new StockData(); CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(); StockPriceDisplay stockPriceDisplay = new StockPriceDisplay(); weatherData.registerObserver(currentConditionsDisplay); stockData.registerObserver(stockPriceDisplay); weatherData.setMeasurements(80, 65, 30.4f); stockData.setPrice(100); ``` 这就是Java中的三种常用设计模式简单示例。希望对您有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值