package strategy
import "fmt"
type Strategy interface {
doPromotion()
}
type Activity struct {
strategy Strategy
}
func NewActivity(strategy Strategy) *Activity {
return &Activity{strategy: strategy}
}
func (a Activity) executeStrategy() {
a.strategy.doPromotion()
}
type FanXianStratege struct {
}
func NewFanXianStratege() *FanXianStratege {
return &FanXianStratege{}
}
func (FanXianStratege) doPromotion() {
fmt.Println("返现促销")
}
type LiJianStrategy struct {
}
func NewLiJianStrategy() *LiJianStrategy {
return &LiJianStrategy{}
}
func (LiJianStrategy) doPromotion() {
fmt.Println("立减促销")
}
type ManJianStrategy struct {
}
func NewManJianStrategy() *ManJianStrategy {
return &ManJianStrategy{}
}
func (ManJianStrategy) doPromotion() {
fmt.Println("满减促销")
}
package strategy
import "testing"
func Test(t *testing.T) {
activity618 := NewActivity(NewFanXianStratege())
activity1111 := NewActivity(NewLiJianStrategy())
activity618.executeStrategy()
activity1111.executeStrategy()
}
package tech.selinux.design.pattern.behavioral.strategy;
public interface Strategy {
void doPromotion();
}
package tech.selinux.design.pattern.behavioral.strategy;
public class Activity {
private Strategy strategy;
public Activity(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.doPromotion();
}
}
package tech.selinux.design.pattern.behavioral.strategy;
public class FanXianStrategy implements Strategy {
@Override
public void doPromotion() {
System.out.println("返现促销");
}
}
package tech.selinux.design.pattern.behavioral.strategy;
public class LiJianStrategy implements Strategy {
@Override
public void doPromotion() {
System.out.println("立减促销");
}
}
package tech.selinux.design.pattern.behavioral.strategy;
public class ManJianStrategy implements Strategy {
@Override
public void doPromotion() {
System.out.println("满减促销");
}
}
package tech.selinux.design.pattern.behavioral.strategy;
public class Test {
public static void main(String[] args) {
Activity activity618 = new Activity(new LiJianStrategy());
Activity activity1111 = new Activity(new FanXianStrategy());
activity618.executeStrategy();
activity1111.executeStrategy();
}
}
package tech.selinux.design.pattern.behavioral.strategy;
import org.apache.commons.lang3.StringUtils;
public class Test {
public static void main(String[] args) {
// Activity activity618 = new Activity(new LiJianStrategy());
// Activity activity1111 = new Activity(new FanXianStrategy());
//
// activity618.executeStrategy();
// activity1111.executeStrategy();
final String strategy = "LIJIAN";
if (StringUtils.equals(strategy, "LIJIAN")) {
Activity activity = new Activity(new LiJianStrategy());
activity.executeStrategy();
} else if (StringUtils.equals(strategy, "MANJIAN")) {
Activity activity = new Activity(new ManJianStrategy());
activity.executeStrategy();
}
}
}
补充另一个版本的Java/Scala Demo 以及源码解析