عرض عملي: استبدال switch على النوع بنمط Strategy
في هذا الدرس 3 موضوعات
محتوى هذا الدرس مكتوب وينتظر المراجعة. يعرض المخطط أدناه ما سيغطيه، وسيُنشر بعد اعتماده.
نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.
في هذا الدرس
turn a growing switch on shipping type into Strategy. Prepares JNR-005-LAB1.
تفاصيل المخطط المبدئي
خطوة بخطوة
- Show a
switch (shippingType)inShippingCalculatorwith three cases; tests pass. - Extract the
ShippingStrategyinterface and one class per case. - Choose the strategy through a small factory.
- Planned mistake: create a strategy for a case with one line of code and a new file for each trivial detail; the design is heavier than the switch. Fix: use lambdas for tiny strategies, and keep only the meaningful classes.
- Run the tests; add a fourth shipping type with no edit to old classes.
- Say in one line why Strategy was justified here.
اختبر فهمك
When is a lambda enough for a strategy?
أظهر الإجابة
When the behavior is tiny and has no state.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.