设计模式之:装饰者模式

#初始化类

module Traffic

  class SimpleTraffic
     
   def initialize(placement_id,&blk)
      @placement = placement_id
      raise ArgumentError, "Incorrect placement_id" if !activeness_exists?
      @ts = TimeSlot.new
      yield(self) if block_given?
    end

    def index
      @index ||= @ts.index
    end

  end
end

#基础接口

module Traffic
  class TrafficDecorator      
    
    def initialize(traffic)
       @traffic = traffic
    end

    def placement
      @traffic.placement
    end

    def index
      @traffic.index
    end

    def target_creatives
      @target_creatives ||=  original_priority_creatives.empty? ? (@active_creatives - assign_creatives) : @active_creatives
    end

  end
end

#装饰对象1:
module Traffic
  class TrafficGeo < TrafficDecorator

    LOCATIONCREATIVEKEY = "LOCATION_CREATIVES"

    def initialize(traffic)  
        super(traffic)  
        @targets = location_creatives
    end  

    #过滤方法
    def target_creatives  
      @target_creatives ||= @traffic.target_creatives & @targets
    end

end


#装饰对象2:
module Traffic

  class TrafficParting < TrafficDecorator

    def initialize(traffic)  
        super(traffic)    
    end  

    #过滤条件
    def target_creatives  
      @target_creatives ||= get_time_parting_creatives
    end

    private   
       
      def get_time_parting_creatives 
        @traffic.target_creatives.select{|creative_id| Creative.new(creative_id).deliverable?(index) }
      end

  end
end

#装饰对象3:
module Traffic
  class TrafficGroup < TrafficDecorator

  
    def initialize(traffic)  
        super(traffic)  
    end  

    def target_creatives  

      return @target_creatives if @target_creatives

      if @traffic.original_priority_creatives.empty?

        @target_creatives = get_goal_creatives 

      else

        @target_creatives = @traffic.original_priority_creatives & @traffic.target_creatives
        
      end

      @target_creatives

    end

    private   
       
      def get_goal_creatives 
        @traffic.target_creatives.select do |creative_id| 
            creative = Creative.new(creative_id)
            creative.traffic_features = feature
            creative.exact_match?
        end
      end

  end
end

-------------------------------------------------------------------------

执行调用:

traffic = Traffic::SimpleTraffic.new(opxplacement_id) do |tfc|

    tfc.cookie = env["HTTP_COOKIE"]

    tfc.server_name = env["SERVER_NAME"]

end

geo = Traffic::TrafficGeo.new(traffic)

unless geo.target_creatives.empty?

    tmpt = Traffic::TrafficParting.new(geo)

unless tmpt.target_creatives.empty?

    crowd = Traffic::TrafficGroup.new(tmpt)

end
end

你可能感兴趣的:(设计模式)