النموذج Strategy

الوقت المقدر للقراءة 10 دقيقة.

وصف النموذج

هو نموذج سلوكي يسمح لصف معين بتغيير سلوكه أو خوارزمية العمل الخاصة به بشكل ديناميكي أثناء التنفيذ.

متى نستخدم النموذج Strategy

يمكن أن يستخدم في التطبيقات التي تحتاج إلى نوع من الذكاء الصنعي مثل الألعاب التي تحتاج الكائنات فيها إلى تغيير سلوكها بشكل آلي حسب معطيات معينة.

كيف يعمل النموذج Strategy

يتكون هذا النموذج مما يلي:

الصف Context الذي يرغب بتغيير سلوكه بشكل ديناميكي أثناء تنفيذ البرنامج.

الصف Strategy الذي يمثل سلوك مجرد.

الصفوف التي تحقق الصف Strategy والتي يمثل كل منها سلوك معين.

/**
 *
 * @author Mutasem
 */
public abstract class Strategy {
    public abstract void execute();
}

/******************************/
public class Strategy1 extends Strategy{

    @Override
    public void execute() {
        System.out.println("Strategy1.execute()");
    }
    
}

/*****************************/
public class Strategy2 extends Strategy{

    @Override
    public void execute() {
        System.out.println("Strategy2.execute()");
    }
    
}

/*************************/
public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public Strategy getStrategy() {
        return strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    public void work(){
    strategy.execute();
    }
}

رابط السلسلة على GitHub

https://github.com/mutasemhajhasan/Design-Patterns

المراجع

Gamma, Erich ; Helm, Richard ; Johnson , Ralph ; Vlissides , John;. (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Hawthorne, New York: Addison-Wesley.