An app tells its users about news in different ways: some get an email, some get a text message, an SMS. The code that sends the news shouldn't care which kind each user picked. It only needs to know that each one can send a message. That promise is an interface.
Write:
- the interface
Notifier, with one method,send(message), which returns the text that would be sent; EmailNotifier, created byNewEmailNotifier(address), a notifier whosesendreturns"To ", the address,": "and the whole message;SmsNotifier, created byNewSmsNotifier(phone), a notifier whosesendreturns"SMS ", the phone number,": "and only the first 20 characters of the message (a message of 20 characters or fewer is sent whole);- a function
notifyAll(notifiers, message), which gets a list of notifiers of any kind and returns the list of the texts they send, in the same order.
notifyAll must work through the interface: it calls send on each notifier and never checks which kind of notifier it is.
Go has no classes and no implements: Notifier is an interface type, EmailNotifier and SmsNotifier are structs, and a struct that has the method send(message string) string is a Notifier without saying so. NewEmailNotifier(address) and NewSmsNotifier(phone) create them, and notifyAll is a plain function that gets a []Notifier.
The program creates the notifiers listed in the input, calls notifyAll once for each message, and prints each text it returns on its own line.
Example 1:
Input:
notifiers: NewEmailNotifier("ana@mail.com"), NewSmsNotifier("0712345678")
message: "Meeting at 5"
Output:
To ana@mail.com: Meeting at 5
SMS 0712345678: Meeting at 5
Explanation: The message has 12 characters, so the SMS sends all of it too.
Example 2:
Input:
notifiers: NewSmsNotifier("5550100"), NewEmailNotifier("bob@work.org")
message: "Your order has shipped today"
Output:
SMS 5550100: Your order has shipp
To bob@work.org: Your order has shipped today
Explanation: The message has 28 characters. The SMS keeps the first 20, "Your order has shipp";
the email sends all of it. The texts come in the order of the notifiers.
Example 3:
Input:
notifiers: NewSmsNotifier("111"), NewSmsNotifier("222")
messages: "Exactly twenty chars", "Exactly twenty chars!"
Output:
SMS 111: Exactly twenty chars
SMS 222: Exactly twenty chars
SMS 111: Exactly twenty chars
SMS 222: Exactly twenty chars
Explanation: notifyAll is called once for each message, with the same two notifiers.
The first message has exactly 20 characters and is sent whole. The second has 21, so its "!" is cut.
Constraints:
- There are at most 50 notifiers. There can be none: then
notifyAllreturns an empty list. - A message has 1 to 100 characters: letters, digits, spaces and punctuation, with no space at its start or end.
- Addresses and phone numbers have no spaces.
Free plan: 30 tutor messages. PRO is unlimited.
