FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries.

Slides:



Advertisements
Similar presentations
Composite: Shapes Organisation State Observer Design Patterns.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Design Patterns Examples of smart use of inheritance and polymorphism: Composite Pattern State Pattern FEN 2014UCN Teknologi/act2learn1.
Road Map Introduction to object oriented programming. Classes
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
2.3 Cool features in C# academy.zariba.com 1. Lecture Content 1.Extension Methods 2.Anonymous Types 3.Delegates 4.Action and Func 5.Events 6.Lambda Expressions.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Delegates and Events Tom Roeder CS fa. Motivation – Function Pointers Treat functions as first-class objects eg. Scheme: (map myfunc somelist)
Abstract Data Types and Encapsulation Concepts
1 One-Dimensional Arrays  What are and Why 1-D arrays?  1-D Array Declaration  Accessing elements of a 1-D Array  Initializer List  Passing Array.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
PARALLEL PROGRAMMING ABSTRACTIONS 6/16/2010 Parallel Programming Abstractions 1.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
Java Generics.
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
FEN 2012 UCN Technology: Computer Science1 C# - Introduction Language Fundamentals in Brief.
4.1 Instance Variables, Constructors, and Methods.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Chapter 4 Introduction to Classes, Objects, Methods and strings
Lambda Expressions Version 1.0
Data Parallelism Task Parallel Library (TPL) The use of lambdas Map-Reduce Pattern FEN 20141UCN Teknologi/act2learn.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Introduction to Object-Oriented Programming Lesson 2.
The Visitor Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
1.NETDelegates & eventsNOEA / PQC Delegates & events Observer pattern Delegates –Semantics –Cil – kode –Anvendelse Events.
From C++ to C# Part 5. Enums Similar to C++ Similar to C++ Read up section 1.10 of Spec. Read up section 1.10 of Spec.
1 Design Patterns Delegates Visitor Pattern. 2 Observer Pattern Observer Pattern is an object-oriented design that simulates void-pointers in for instance.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
int [] scores = new int [10];
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – kode –Anvendelse Events.
1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – code –Usage Events Asynchronious delegates.
Lambdas and Streams. Stream manipulation Class Employee represents an employee with a first name, last name, salary and department and provides methods.
OOP in C# - part 1 OOP in C#: –Object Interaction. –Inheritance and Polymorphism (next module). FEN 20121UCN Technology: Computer Science.
Lambda Functions & Closures A Sydney PHP Group Presentation 2 nd October 2008 By Timothy Chandler.
Abstract Data Types and Encapsulation Concepts
CS 326 Programming Languages, Concepts and Implementation
Interface Java 7 COMP T1.
Delegates and Events 14: Delegates and Events
Methods Attributes Method Modifiers ‘static’
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Generics, Lambdas, Reflections
Abstract Data Types and Encapsulation Concepts
6 Delegate and Lambda Expressions
Abstract Data Types and Encapsulation Concepts
int [] scores = new int [10];
Delegates & Events 1.
Object Oriented Practices
Closure Closure binds a first-class function and a lexical environment together This is a complex topic, so we will build up our understanding of it we.
Lesson 7. Events, Delegates, Generics.
int [] scores = new int [10];
Generics, Lambdas, Reflections
Chengyu Sun California State University, Los Angeles
Presentation transcript:

FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries

Problem: –An unknown number of clients (observers) want to be notified, when some object change state. –Example: Ib’s cognac bottle: FEN 2014UCN Teknologi/act2learn2 Observer Pattern

FEN 2014UCN Teknologi/act2learn3 Observer Pattern Drinker_1 Drinker_2 Drinker_N Drinker_I Drinks (change state) Notify

Design Requirements: –Drinkers should be able to come and go (add and remove observers). –Drinkers should know as little as possible about how state is represented in the bottle. –The bottle should know as little as possible about the observers. –Drinkers may react differently on the notification about state change. FEN 2014UCN Teknologi/act2learn4 Observer Pattern

Solution: Observer Pattern FEN 2014UCN Teknologi/act2learn5

FEN 2014UCN Teknologi/act2learn 6 Observer Pattern (Call-back) A number of different objects (observers) wants to be notified when some given object (observable or subject) changes state. Subject must allow observers to enrol dynamically, and subject shall have no knowledge about the observers. This pattern is in sometimes known as call-back.

FEN 2014UCN Teknologi/act2learn7 Observer Pattern Example: a number of objects are interested in being told when some other object is changing state. These objects (the observers) must implement the interface IObserver. This means implementing the method NotifyMe. This method will be called when the observed object (subject) changes state. Subject must maintain a collection of observers and be able to notify all objects in the collection (IObservable). Subject calls NotifyAll, when a change in state happens See it work

Exercise Add a Realist to the example. A realist will act as a pessimist, if the bottle amount is less than 50 cl. and like an optimist otherwise. Make a method on BottleState that fills the bottle (amount = 70); (Extra): Refactor the observer example, so all the code to handle observers are placed in an abstract class. The method NotityAll() is to be abstract. The subject (BottleState) is to inherit the abstract class and implement NotifyAll(). FEN 2014UCN Teknologi/act2learn8

FEN 2014UCN Teknologi/act2learn9 Observer Pattern and delegates Observer Pattern is an object-oriented design that simulates void-pointers in for instance C/C++ and higher order functions in for instance Pascal and functional languages. In C# the language construct delegate provides some of the same possibilities.

Delegates A delegate is a language construct that facilitates passing methods as parameters to other methods. This can be done both for instance and class methods. This can be done across objects and classes. Delegates are object oriented and type safe. Actual, a delegate is an object which contains a collection of methods that may be invoked. FEN 2014UCN Teknologi/act2learn10

Observer Delegate These features can be used to implement call-back: View: code samplecode sample FEN 2014UCN Teknologi/act2learn11

Delegates: The delegate must be defined. The observers must implement a method with the signature (return type and parameter list) as the delegate. FEN 2014UCN Teknologi/act2learn12 namespace DelegateExample { delegate void Drinkers(int amount); //Declare the delegate's signature class DelegateDemo { static void Main(string[] args) //--- class Optimist { public void NotifyMe(int amount) { Console.WriteLine("There is still left: “ +amount+" cl of cognac:-)"); } //---

Delegates: A delegate is declared. The observers NotifyMe method are added to the delegate. Change state methods of the observable take the delegate as parameter. When the observable change state, all methods in the delegate is called. Note the check for not null! FEN 2014UCN Teknologi/act2learn13 //--- Drinkers myDrinkers; BottleState myBottle = new BottleState(); Pessimist ib = new Pessimist(); Optimist kurt = new Optimist(); myDrinkers = ib.NotifyMe; myDrinkers += kurt.NotifyMe; //--- public void ChangeAmount(Drinkers myDrinkers) { Console.Write("Enter new bottleamount: "); this.amount = Convert.ToInt32(Console.ReadLine()); if(myDrinkers != null) myDrinkers(amount); //--- Not nice: The delegate shouldn’t be public

Exercise Add a Realist to the example. A realist will act as a pessimist, if the bottle amount is less than 50 cl. and like an optimist otherwise. FEN 2014UCN Teknologi/act2learn14

Delegates are objects them selves. They inherit from System.Delegate via System.MulticastDelegate FEN 2014UCN Teknologi/act2learn15

Events Delegates are often used for event based systems The keyword event in C# makes this a little easier The mechanism behind is the same. A event is a sort of a specialised delegate. Events are often used in object oriented GUI programs Events can be used with advantage in other areas such as simulation and real-time systems. Example from Troelsen, chap. 10.Example from Troelsen, chap. 10 FEN 2014UCN Teknologi/act2learn16

Visitor Delegate Used for traversing a collection and changing elements without knowing anything about the internal structure of the collections. A sort of “mutator iterator” May be simulated using the Visitor Pattern (GoF 1995) FEN 2014UCN Teknologi/act2learn17 Collection y x z ModifyAll( ) public int Double(int x){ return 2*x; } View: code samplecode sample

Visitor Delegate In the container, define visiting delegates and methods visiting the container. FEN 2014UCN Teknologi/act2learn18 public delegate int ModifyElement(int e); public delegate bool CheckElement(int e); public void ModifyAll(ModifyElement f) { //implement according to data representation } public void ModifySome(ModifyElement f, CheckElement p) { //implement according to data representation }

Visitor Delegate In the client, declare some methods to visit the container. Declare the delegates and add the visitor methods. Visit the container. FEN 2014UCN Teknologi/act2learn19 public static int Double(int x) { return 2*x; } public static bool Even(int x) { return x % 2 == 0; } //--- Container.ModifyElement toDo= Double; Container.CheckElement cond = Even; con1.ModifySome(toDo, cond); //---

Exercise Add methods to the Visitor example, so it is possible to increase all numbers greater than 20 in the container by 7. Test FEN 2014UCN Teknologi/act2learn20

Lambdas Since C# 3.0 lambdas have been part of C#. Lambdas make it possible to work with delegates without explicitly declaring delegates etc. A lambda is an anonymous function witch can be passed to a method that accepts a delegate as parameter. Lambdas are sometimes called lambda expressions. The term “lambda” comes from the theory of functional programming. (Alonzo Church: Lambda Calculus, 1936). FEN 2014UCN Teknologi/act2learn21 View: code samplecode sample

Visitor using lambdas It’s not necessary to declare delegates explicitly. The standard library delegate Func can be used in the visitor method. Call the visitor method on the container supplying two lambda expressions (anonymous methods) as argument. FEN 2014UCN Teknologi/act2learn22 public void ModifySome(Func f, Func p) { //Applies f only to elements in the container //that satisfy p for (int i = 0; i < a.Length; i++) { if (p(a[i])) a[i] = f(a[i]); } //--- con1.ModifySome((x) => 2 * x, (x) => x % 2 == 0); //---

Dissecting the lambda expression FEN 2014UCN Teknologi/act2learn23 //--- con1.ModifySome((x) => 2 * x, (x) => x % 2 == 0); //--- Lambda operator Input parameter Function code (body)

Lambda typing How are lambda expressions typed? Some examples… What’s New24 () => {... } () => {... } Action (i) => {... } (i) => {... } Action () => {... return d; } () => {... return d; } Func (i) => {... return d; } (i) => {... return d; } Func<int, double>

Lambda typing How are lambda expressions typed? Some examples… What’s New25 (i) => {... return d==0; } (i) => {... return d==0; } Predicate View: code samplecode sample

Closures and lambdas Sometimes you may want to use variables in the lambda expression that are not passed as parameters to the lambda: The variable c is defined outside the lambdas scope. The compiler computes the closure of the lambda. The compiler generates a class with the lambda method and the needed variables, and it is actually this class that is passed around. FEN 2014UCN Teknologi/act2learn26 //--- int c = 2; con1.ModifySome((x) => c * x, (x) => x % 2 == 0); //---

Exercise Add code to the lambda example, so all numbers greater than 20 in the container are increased by 7. Add a new higher order function: public it SumSome(int seed, Predicate p) that sums the elements in the container that satisfies p. seed is the start value of the summing. Test by summing, for instance only elements greater than or equal to 20. Generalise your function, so it only sums elements in a given range (from start index to end index). FEN 2014UCN Teknologi/act2learn27

Lambdas in the libraries Lambdas are heavily used in the libraries. Many methods are to be called with a lambda expression as argument: FEN 2014UCN Teknologi/act2learn28 View: code samplecode sample

Exercise Try some of the higher order functions defined on collections. –For instance: Find/FindLast: Find first/last element with Y == 3. FindAll: Find all elements with X==Y Exists/All: Use exists to determine if the list contains (0, 0). Sum: Find the sum of the square of the x’s Average: Find the average of the x’s Count: How many pairs have x != y? Try to change List to some other collection. Which higher order functions do still apply? FEN 2014UCN Teknologi/act2learn29 View: code samplecode sample