Some text from Minecraft Wiki used under Creative Commons Attribution-Share Alike License 3.0
Automatic Melon Farms can be created by planting Melon Seeds where the Melons only have one place to grow, and placing Pistons or Sticky Pistons run by a Redstone Clock next to where the Melons would grow, and Flowing Water flowing into a Hopper on the other side.